In Python 2, sending a HEAD HTTP request can be achieved through several methods, with the most straightforward approach being the use of the httplib library. Below, I will detail how to utilize this library to send a HEAD request.
Using httplib
httplib is a built-in library in Python 2 for handling HTTP requests. Here are the steps to send a HEAD request using httplib:
-
Import the library: First, import the
httpliblibrary.pythonimport httplib -
Establish a connection: Create an HTTP connection to the target server.
pythonconn = httplib.HTTPConnection('www.example.com') -
Send the HEAD request: Use the
requestmethod to send a HEAD request. The HEAD method is one of the pre-defined methods in the HTTP protocol, used to retrieve metadata (such as header information) of a document without fetching the actual content.pythonconn.request("HEAD", "/path") -
Retrieve the response: Obtain the response returned by the server.
pythonres = conn.getresponse() -
Read header information: The primary purpose of a HEAD request is to retrieve header information; you can use the
getheaders()method to obtain all header details.pythonheaders = res.getheaders() print(headers) -
Close the connection: Finally, close the connection to release system resources.
pythonconn.close()
Example Code
Integrating the above steps into a single code snippet:
pythonimport httplib def send_head_request(): # Establish connection to the target server conn = httplib.HTTPConnection('www.example.com') # Send HEAD request conn.request("HEAD", "/path") # Retrieve and process response response = conn.getresponse() headers = response.getheaders() # Print header information print("Status Code:", response.status) print("Headers:") for header in headers: print(header) # Close connection conn.close() # Call the function send_head_request()
In this example, www.example.com should be replaced with the actual domain you wish to query, and /path should be replaced with the actual resource path. This code will print the status code and header information retrieved from the server, which is useful for inspecting metadata of web pages.