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

标签 python python-2.7 http http-headers content-type

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

最佳答案

urllib2可用于执行 HEAD 请求。这比使用 httplib 好一点,因为 urllib2 会为您解析 URL,而不是要求您将 URL 拆分为主机名和路径。

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

headers 可以像以前一样通过 response.info() 获得。有趣的是,您可以找到被重定向到的 URL:

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

关于python - 如何在 Python 2 中发送 HEAD HTTP 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/107405/

相关文章:

java - HTTP 状态 415 – 使用 Angular js 的 Spring MVC 中出现不支持的媒体类型错误

php - 为什么不再有用于 PECL 扩展(如 pecl_http)的 Windows 二进制文件?

python - 在 python 中将各个位写入文件

python - 如何在 python 中将对象作为命令行参数传递?

python - Scapy:嗅探自制层

python - 在Python中创建定时器线程

python - 用户输入的输出字典不正确

.net - .NET 中的 XML HTTP POST 集成

python - 检查sqlite3中是否存在一行?

Python - 计算文本搜索相关性分数的库