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
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!