Sending HEAD HTTP Request in Python 2 for MIME Type Retrieval
This question explores how to send a HEAD request in Python 2 to retrieve only the headers of a URL, allowing us to determine its MIME type without downloading the content.
Using urllib2 for HEAD Request:
The urllib2 library provides a simple solution for this need. It handles URL parsing, making it easier to set up the request, as seen in the following code snippet:
<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>
This effectively sends a HEAD request to the specified URL and stores the response in the 'response' variable.
Retrieving Headers:
Headers are accessible through the 'response.info()' method, as shown below:
<code class="python">headers = response.info()</code>
Now you have access to the MIME type and other header information for the requested URL. Additionally, the 'response.geturl()' method reveals the final URL you were redirected to, if any.
The above is the detailed content of How to Retrieve MIME Type Using a HEAD Request in Python 2?. For more information, please follow other related articles on the PHP Chinese website!