Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set headers using python's urllib?

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.

like image 943
ewok Avatar asked Oct 28 '11 18:10

ewok


People also ask

How do you pass a header URL in Python?

HTTP headers let the client and the server pass additional information with an HTTP request or response. All the headers are case-insensitive, headers fields are separated by colon, key-value pairs in clear-text string format.

Which is better Urllib or requests?

True, if you want to avoid adding any dependencies, urllib is available. But note that even the Python official documentation recommends the requests library: "The Requests package is recommended for a higher-level HTTP client interface."


2 Answers

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) 
like image 199
Cees Timmerman Avatar answered Oct 11 '22 22:10

Cees Timmerman


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() 
like image 27
Corey Goldberg Avatar answered Oct 11 '22 22:10

Corey Goldberg