How do I set headers using python's urllib?

ewok picture ewok · Oct 28, 2011 · Viewed 132.5k times · Source

I am pretty new to python's urllib. What I need to do is set a custom header for the request being sent to the server. Specifically, I need to set the Content-type and Authorizations headers. I have looked into the python documentation, but I haven't been able to find it.

Answer

Corey Goldberg picture Corey Goldberg · Oct 28, 2011

adding HTTP headers using urllib2:

from the docs:

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
resp = urllib2.urlopen(req)
content = resp.read()