Passing HTTP headers

December 21, 2011
Passing HTTP headers using urllib2 is a straightforward thing.

def logIn(self):
  req = urllib2.Request(self.login_url)
  req.add_header('Host', 'foo.com')
  req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; rv:6.0) Gecko/20100101 Firefox/6.0')
  req.add_header('Accept-Language', 'en-us,en')
You can also put everything in a dictionary:

headers = {
  'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:6.0) Gecko/20100101 Firefox/6.0',
  'Accept-Language':'en-us,en',
  'Content-Type': 'application/x-www-form-urlencoded'
}
And then just execute your query:

req = urllib2.Request(self.login_url, form_data, headers)
log_in = urllib2.urlopen(req).read()