如何在不下载的情况下检查对象的HTTP状态代码? [英] How do I check the HTTP status code of an object without downloading it?

查看:131
本文介绍了如何在不下载的情况下检查对象的HTTP状态代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> a=urllib.urlopen('http://www.domain.com/bigvideo.avi')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200

我的问题是... bigvideo.avi是500MB 。我的脚本是否首先下载文件,然后检查它?或者,它可以立即检查错误代码而不保存文件吗?

My question is...bigvideo.avi is 500MB. Does my script first download the file, then check it? Or, can it immediately check the error code without saving the file?

推荐答案

您想要实际告诉服务器 发送文件的完整内容。 HTTP有一种称为HEAD的机制,它是GET的替代品。它的工作方式相同,但服务器只向您发送标题,而不是实际内容。

You want to actually tell the server not to send the full content of the file. HTTP has a mechanism for this called "HEAD" that is an alternative to "GET". It works the same way, but the server only sends you the headers, none of the actual content.

这样可以节省至少一个带宽,而不是做一个read()只会打扰得到完整的文件。

That'll save at least one of you bandwidth, while simply not doing a read() will only not bother getting the full file.

试试这个:

import httplib
c = httplib.HTTPConnection(<hostname>)
c.request("HEAD", <url>)
print c.getresponse().status

将打印状态代码。网址应该只是一个细分受众群,例如/ foo,主机名应该像www.example.com。

The status code will be printed. Url should only be a segment, like "/foo" and hostname should be like, "www.example.com".

这篇关于如何在不下载的情况下检查对象的HTTP状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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