Home  >  Article  >  Backend Development  >  How to Send a HEAD HTTP Request in Python 2 with urllib2?

How to Send a HEAD HTTP Request in Python 2 with urllib2?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 12:21:29861browse

How to Send a HEAD HTTP Request in Python 2 with urllib2?

How to Send a HEAD HTTP Request in Python 2 with urllib2

To obtain the headers of a specific URL and determine its MIME type, one must send a HEAD request. This differs from a GET request as it retrieves the headers without downloading the resource.

Python 2 Implementation:

urllib2, a high-level interface, simplifies the process of sending HEAD requests:

<code class="python">import urllib2

class HeadRequest(urllib2.Request):
    def get_method(self):
        return "HEAD"

response = urllib2.urlopen(HeadRequest("http://google.com/index.html"))</code>

Response Object:

The response object from HEAD contains the headers, accessible via response.info(). It also provides the redirect URL:

<code class="python">print(response.geturl())  # Output: http://www.google.com.au/index.html</code>

The above is the detailed content of How to Send a HEAD HTTP Request in Python 2 with urllib2?. 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