http – Python – make a POST request using Python 3 urllib

http – Python – make a POST request using Python 3 urllib

This is how you do it.

from urllib import request, parse
data = parse.urlencode(<your data dict>).encode()
req =  request.Request(<your url>, data=data) # this will make the method POST
resp = request.urlopen(req)

Thank you C Panda. You really made it easy for me to learn this module.

I released the dictionary that we pass does not encode for me. I had to do a minor change –

from urllib import request, parse
import json

# Data dict
data = { test1: 10, test2: 20 }

# Dict to Json
# Difference is { test:10, test2:20 }
data = json.dumps(data)

# Convert to String
data = str(data)

# Convert string to byte
data = data.encode(utf-8)

# Post Method is invoked if data != None
req =  request.Request(<your url>, data=data)

# Response
resp = request.urlopen(req)

http – Python – make a POST request using Python 3 urllib

The above code encoded the JSON string with some extra that caused me a lot of problems. This looks like a better way of doing it:

from urllib import request, parse

url = http://www.example.com/page

data = {test1: 10, test2: 20}
data = parse.urlencode(data).encode()

req = request.Request(url, data=data)
response = request.urlopen(req)

print (response.read())

Leave a Reply

Your email address will not be published. Required fields are marked *