Search code examples
pythonurllib2urllib3

Python urllib2 -> urllib3 request.urlopen


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. enter image description here

With python3 it looks like:

enter image description here

So how can I user urllib3 with the same output as urllib2?


Solution

  • 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
    )