Python - make a POST request using Python 3 urllib Python - make a POST request using Python 3 urllib python python

Python - make a POST request using Python 3 urllib


This is how you do it.

from urllib import request, parsedata = 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, parseimport json# Data dictdata = { 'test1': 10, 'test2': 20 }# Dict to Json# Difference is { "test":10, "test2":20 }data = json.dumps(data)# Convert to Stringdata = str(data)# Convert string to bytedata = data.encode('utf-8')# Post Method is invoked if data != Nonereq =  request.Request(<your url>, data=data)# Responseresp = request.urlopen(req)


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, parseurl = "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())