Home > Backend Development > Python Tutorial > 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
Release: 2024-11-01 12:21:29
Original
975 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template