How do you send a HEAD HTTP request in Python 2?

前端 未结 11 2108
甜味超标
甜味超标 2020-11-22 11:40

What I\'m trying to do here is get the headers of a given URL so I can determine the MIME type. I want to be able to see if http://somedomain/foo/ will return a

11条回答
  •  一个人的身影
    2020-11-22 11:56

    urllib2 can be used to perform a HEAD request. This is a little nicer than using httplib since urllib2 parses the URL for you instead of requiring you to split the URL into host name and path.

    >>> import urllib2
    >>> class HeadRequest(urllib2.Request):
    ...     def get_method(self):
    ...         return "HEAD"
    ... 
    >>> response = urllib2.urlopen(HeadRequest("http://google.com/index.html"))
    

    Headers are available via response.info() as before. Interestingly, you can find the URL that you were redirected to:

    >>> print response.geturl()
    http://www.google.com.au/index.html
    

提交回复
热议问题