Python urllib2 -> urllib3 request.urlopen

huangapple go评论65阅读模式
英文:

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.
Python urllib2 -> urllib3 request.urlopen

With python3 it looks like:

Python urllib2 -> urllib3 request.urlopen

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
)

huangapple
  • 本文由 发表于 2023年4月4日 15:19:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75926525.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定