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

前端 未结 11 1992
甜味超标
甜味超标 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:41

    edit: This answer works, but nowadays you should just use the requests library as mentioned by other answers below.


    Use httplib.

    >>> import httplib
    >>> conn = httplib.HTTPConnection("www.google.com")
    >>> conn.request("HEAD", "/index.html")
    >>> res = conn.getresponse()
    >>> print res.status, res.reason
    200 OK
    >>> print res.getheaders()
    [('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')]
    

    There's also a getheader(name) to get a specific header.

提交回复
热议问题