乐闻世界logo
搜索文章和话题

How do you send a HEAD HTTP request in Python 2?

1个答案

1

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:

  1. Import the library: First, import the httplib library.

    python
    import httplib
  2. Establish a connection: Create an HTTP connection to the target server.

    python
    conn = httplib.HTTPConnection('www.example.com')
  3. Send the HEAD request: Use the request method 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.

    python
    conn.request("HEAD", "/path")
  4. Retrieve the response: Obtain the response returned by the server.

    python
    res = conn.getresponse()
  5. 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.

    python
    headers = res.getheaders() print(headers)
  6. Close the connection: Finally, close the connection to release system resources.

    python
    conn.close()

Example Code

Integrating the above steps into a single code snippet:

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

2024年8月5日 01:59 回复

你的答案