Home > Article > Backend Development > 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:
<code class="python">import urllib2</code>
<code class="python">class HeadRequest(urllib2.Request): def get_method(self): return "HEAD"</code>
<code class="python">request = HeadRequest("http://somedomain/foo/")</code>
<code class="python">response = urllib2.urlopen(request)</code>
<code class="python">headers = response.info()</code>
<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!