Not possible to set content-type to application/json using urllib2

I got hit by the same stuff and came up with this little gem:

import urllib2
import simplejson as json

class ChangeTypeProcessor(BaseHandler):
    def http_request(self, req):
        req.unredirected_hdrs["Content-type"] = "application/json"
        return req

opener = urllib2.build_opener()
self.opener.add_handler(ChangeTypeProcessor())
response = opener.open('http://localhost:8000',json.dumps({'a': 'b'}))

You just add a handler for HTTP requests that replaces the header that OpenerDirector previously added.


If you want to set custom headers you should use a Request object:

import urllib2
import simplejson as json

opener = urllib2.build_opener()
req = urllib2.Request('http://localhost:8000', data=json.dumps({'a': 'b'}),
      headers={'Content-Type': 'application/json'})
response = opener.open(req)