Making A Post Request Using Urllib With Multiple Headers Gives 400 Bad Request Error
I have used requests library and I know how to work with it, but I need to work with standard library only, so I would appreciate if you don't encourage me to use requests instead.
Solution 1:
The server is failing in request.get_json()
. It's only happening when the client sends both headers because that's when it reaches this line.
To fix it, change the client to send the data as JSON:
import json # <-- Import json
import urllib.request
import urllib.parse
d = {"spam": 1, "eggs": 2, "bacon": 0}
data = json.dumps(d) # <-- Dump the dictionary as JSON
data = data.encode()
req = urllib.request.Request("http://localhost:5000/random", data)
req.add_header('Content-Type', 'application/json')
req.add_header('Authorization', 12345)
with urllib.request.urlopen(req) as f:
print(f.read().decode('utf-8'))
I hope this helps
Post a Comment for "Making A Post Request Using Urllib With Multiple Headers Gives 400 Bad Request Error"