How do I set HTTP headers using Python's urllib?
Asked Answered
N

4

110

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.

Nardi answered 28/10, 2011 at 18:39 Comment(0)
L
107

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()
Labyrinthodont answered 28/10, 2011 at 18:53 Comment(0)
G
140

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)
Germ answered 21/7, 2014 at 16:37 Comment(4)
Can we do the same thing with requests q.add_header('apikey', 'xxx')Haymaker
What do you mean, @user3378649?Germ
@Haymaker may be you means use requests python package custom headersHierophant
THIS answer - a thousand times YES (thanks!). I have been struggling for hours trying to find a common interface for python 2 and 3 (between urllib, urllib2 and urllib3).Recount
L
107

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()
Labyrinthodont answered 28/10, 2011 at 18:53 Comment(0)
E
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....

Erine answered 28/10, 2011 at 18:44 Comment(0)
C
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()
Chloechloette answered 26/5, 2015 at 8:39 Comment(2)
Do not do this, simply pass in a headers dictionary if you have multiple header fields to use.Surtax
guess you are right - but hey, this was 2015 for Python 2.7 Theses days - I'm populating a dictionary.Chloechloette

© 2022 - 2024 — McMap. All rights reserved.