102

I am pretty new to Python's urllib. What I need to do is set a custom HTTP header for the request being sent to the server.

Specifically, I need to set the Content-Type and Authorization HTTP headers. I have looked into the Python documentation, but I haven't been able to find it.

informatik01
  • 16,038
  • 10
  • 74
  • 104
ewok
  • 20,148
  • 51
  • 149
  • 254

4 Answers4

132

For both Python 3 and Python 2, this works:

try:
    from urllib.request import Request, urlopen  # Python 3
except ImportError:
    from urllib2 import Request, urlopen  # Python 2

req = Request('http://api.company.com/items/details?country=US&language=en')
req.add_header('apikey', 'xxx')
content = urlopen(req).read()

print(content)
Kir Chou
  • 2,980
  • 1
  • 36
  • 48
Cees Timmerman
  • 17,623
  • 11
  • 91
  • 124
103

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()
Lars Blumberg
  • 19,326
  • 11
  • 90
  • 127
Corey Goldberg
  • 59,062
  • 28
  • 129
  • 143
22

Use urllib2 and create a Request object which you then hand to urlopen. http://docs.python.org/library/urllib2.html

I dont really use the "old" urllib anymore.

req = urllib2.Request("http://google.com", None, {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'})
response = urllib2.urlopen(req).read()

untested....

sleeplessnerd
  • 21,853
  • 1
  • 25
  • 29
1

For multiple headers do as follow:

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('param1', '212212')
req.add_header('param2', '12345678')
req.add_header('other_param1', 'sample')
req.add_header('other_param2', 'sample1111')
req.add_header('and_any_other_parame', 'testttt')
resp = urllib2.urlopen(req)
content = resp.read()
rkosegi
  • 14,165
  • 5
  • 50
  • 83
Gil Allen
  • 1,169
  • 14
  • 24