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

How do you send a HEAD HTTP request in Python 2?(如何在 Python 2 中发送 HEAD HTTP 请求?)
本文介绍了如何在 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:这个答案有效,但现在你应该只使用 requests 库,如下面的其他答案所述.

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(name) 来获取特定的标头.

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)