urllib2 and json

pup picture pup · Jul 20, 2010 · Viewed 101.8k times · Source

can anyone point out a tutorial that shows me how to do a POST request using urllib2 with the data being in JSON format?

Answer

Bob Van Zant picture Bob Van Zant · Feb 15, 2011

Messa's answer only works if the server isn't bothering to check the content-type header. You'll need to specify a content-type header if you want it to really work. Here's Messa's answer modified to include a content-type header:

import json
import urllib2
data = json.dumps([1, 2, 3])
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()