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

Get Mastering Python for Networking and Security now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.