英文:
Python urllib2 -> urllib3 request.urlopen
问题
我需要从urllib2切换到urllib3。存在一个请求问题。
python2 代码:
reqdata = '{"PM1OBJ1":{"FREQ":"","U_AC":"","I_AC":"","P_AC":"","P_TOTAL":""}}'
response = urllib2.urlopen('http://'+ ipaddress +'/lala.cgi', data=reqdata)
python3 代码:
reqdata = {"PM1OBJ1":{"FREQ":"","U_AC":"","I_AC":"","P_AC":"","P_TOTAL":""}}
mydata = urllib.parse.urlencode(reqdata)
mydata = mydata.encode('ascii') # 数据应该是字节
response = urllib.request.urlopen('http://'+ ipaddress +'/lala.cgi', mydata)
当我使用Wireshark进行调试时,我看到python2下的reqdata被传输为字符串。
使用python3时,看起来像这样:
那么如何使用urllib3获得与urllib2相同的输出呢?
英文:
I need to switch from urllib2 to urllib3. There is a problem with a request.
python2 code:
reqdata='{"PM1OBJ1":{"FREQ":"","U_AC":"","I_AC":"","P_AC":"","P_TOTAL":""}}'
response = urllib2.urlopen('http://'+ ipaddress +'/lala.cgi' ,data=reqdata)
python3 code:
reqdata={"PM1OBJ1":{"FREQ":"","U_AC":"","I_AC":"","P_AC":"","P_TOTAL":""}}
mydata = urllib.parse.urlencode(reqdata)
mydata = mydata.encode('ascii') # data should be bytes
response = urllib.request.urlopen('http://'+ ipaddress +'/lala.cgi', mydata)
When I use Wireshare for debugging I see that the reqdata under pythen2 is transmittet as string.
With python3 it looks like:
So how can I user urllib3 with the same output as urllib2?
答案1
得分: 0
你可以使用 PoolManager
类来进行请求,确保已正确安装 urllib3,然后这是你修改后的代码:
import urllib3
import json
ipaddress = "your_ip_address_here"
reqdata = {"PM1OBJ1": {"FREQ": "", "U_AC": "", "I_AC": "", "P_AC": "", "P_TOTAL": ""}}
headers = {'Content-Type': 'application/json'}
http = urllib3.PoolManager()
response = http.request(
'POST',
'http://' + ipaddress + '/lala.cgi',
body=json.dumps(reqdata).encode('ascii'),
headers=headers
)
英文:
You could use the PoolManager
class for the request, be sure to have urllib3 properly installed, then here is your modified code:
import urllib3
import json
ipaddress = "your_ip_address_here"
reqdata = {"PM1OBJ1": {"FREQ": "", "U_AC": "", "I_AC": "", "P_AC": "", "P_TOTAL": ""}}
headers = {'Content-Type': 'application/json'}
http = urllib3.PoolManager()
response = http.request(
'POST',
'http://' + ipaddress + '/lala.cgi',
body=json.dumps(reqdata).encode('ascii'),
headers=headers
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论