[python] 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.

This question is related to python http header urllib

The answer is


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)

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()

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....


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to http

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Axios Delete request with body and headers? Read response headers from API response - Angular 5 + TypeScript Android 8: Cleartext HTTP traffic not permitted Angular 4 HttpClient Query Parameters Load json from local file with http.get() in angular 2 Angular 2: How to access an HTTP response body? What is HTTP "Host" header? Golang read request body Angular 2 - Checking for server errors from subscribe No 'Access-Control-Allow-Origin' header in Angular 2 app How to add header row to a pandas DataFrame How can I make sticky headers in RecyclerView? (Without external lib) Adding header to all request with Retrofit 2 Python Pandas Replacing Header with Top Row Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers Pythonically add header to a csv file fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected? correct PHP headers for pdf file download How to fix a header on scroll

Examples related to urllib

installing urllib in Python3.6 SSL: CERTIFICATE_VERIFY_FAILED with Python3 Python: Importing urllib.quote Python 2.7.10 error "from urllib.request import urlopen" no module named request python save image from url no module named urllib.parse (How should I install it?) 'module' has no attribute 'urlencode' urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error UnicodeEncodeError: 'charmap' codec can't encode characters replace special characters in a string python