Home > Backend Development > Python Tutorial > How to Retrieve MIME Type Using a HEAD Request in Python 2?

How to Retrieve MIME Type Using a HEAD Request in Python 2?

Patricia Arquette
Release: 2024-11-01 13:08:30
Original
1052 people have browsed it

How to Retrieve MIME Type Using a HEAD Request in Python 2?

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

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

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!

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