如何在Python 2中发送HEAD HTTP请求?

我在这里尝试做的是获取给定URL的标头,以便确定MIME类型。我希望能够查看是否http://somedomain/foo/将返回例如HTML文档或JPEG图像。因此,我需要弄清楚如何发送HEAD请求,以便无需下载内容就可以读取MIME类型。有人知道这样做的简单方法吗?

回答:

使用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')]

还有一个getheader(name)获取特定的标头。

以上是 如何在Python 2中发送HEAD HTTP请求? 的全部内容, 来源链接: utcz.com/qa/408003.html

回到顶部