Home >Backend Development >Python Tutorial >How Do You Send HEAD HTTP Requests in Python 2?

How Do You Send HEAD HTTP Requests in Python 2?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 06:42:02727browse

How Do You Send HEAD HTTP Requests in Python 2?

Sending HEAD HTTP Requests in Python 2

In web development, often it is necessary to retrieve the headers of a URL without downloading the content itself. This technique is useful for determining the MIME type of a resource, verifying the existence of a file, or handling redirections. In Python 2, sending HEAD requests is straightforward using the urllib2 module.

To send a HEAD request, follow these steps:

  1. Import the urllib2 module:
<code class="python">import urllib2</code>
  1. Define a custom HTTP request class that overrides the request method with "HEAD":
<code class="python">class HeadRequest(urllib2.Request):
    def get_method(self):
        return "HEAD"</code>
  1. Create an HTTP request object using the custom request class:
<code class="python">request = HeadRequest("http://somedomain/foo/")</code>
  1. Open the request:
<code class="python">response = urllib2.urlopen(request)</code>
  1. Access the headers using response.info():
<code class="python">headers = response.info()</code>
  1. If there was a redirection, you can retrieve the new URL using response.geturl():
<code class="python">redirected_url = response.geturl()</code>

By following these steps, you can easily send HEAD HTTP requests in Python 2 to obtain the headers of web resources without downloading their content.

The above is the detailed content of How Do You Send HEAD HTTP Requests in Python 2?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn