urllib2 and json urllib2 and json json json

urllib2 and json


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 jsonimport urllib2data = json.dumps([1, 2, 3])req = urllib2.Request(url, data, {'Content-Type': 'application/json'})f = urllib2.urlopen(req)response = f.read()f.close()


Whatever urllib is using to figure out Content-Length seems to get confused by json, so you have to calculate that yourself.

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

Took me for ever to figure this out, so I hope it helps someone else.


Example - sending some data encoded as JSON as a POST data:

import jsonimport urllib2data = json.dumps([1, 2, 3])f = urllib2.urlopen(url, data)response = f.read()f.close()