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.
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.
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."
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)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With