如何在Python 2中发送HEAD HTTP请求? [英] How do you send a HEAD HTTP request in Python 2?

查看:914
本文介绍了如何在Python 2中发送HEAD HTTP请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 an HTML document or a JPEG image for example. Thus, I need to figure out how to send a HEAD request so that I can read the MIME type without having to download the content. Does anyone know of an easy way of doing this?

推荐答案

编辑:这个答案有效,但是现在您应该使用下面其他答案中提到的请求库。

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

使用 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(名称)获取特定标题。

这篇关于如何在Python 2中发送HEAD HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆