Checking HTTP headers with urllib2

HTTP requests consist of two main parts: headers and a body. Headers are the lines of information that contain specific metadata about the response that tells the client how to interpret it. With this module we can check whether the headers can provide information about the web server.

The http_response.headers statement provides the header of the web server. Before we access this property, we need to check whether the code response is equal to 200.

You can find the following code in the urllib_headers_basic.py file:

import urllib2
url = raw_input("Enter the URL ")
http_response = urllib2.urlopen(url)
print 'Status Code: '+ str(http_response.code)
if http_response.code == 200:
print http_response.headers

In the following screenshot, we can see the script executing for the python.org domain:

Also, you can get details on headers:

Another way to retrieve response headers is by using the info() method from the response object, which will return a dictionary:

We can also use the keys() method to get all the response header keys:

>>> print response_headers.keys()
['content-length', 'via', 'x-cache', 'accept-ranges', 'x-timer', 'vary', 'strict-transport-security', 'server', 'age', 'connection', 'x-xss-protection', 'x-cache-hits', 'x-served-by', 'date', 'x-frame-options', 'content-type', 'x-clacks-overhead']
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.88.54