How do I check the HTTP status code of an object w

2019-02-14 18:24发布

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

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?

标签: python http
3条回答
淡お忘
2楼-- · 2019-02-14 18:47

Yes, it will fetch the file.

I think what you really want to do is send a HTTP HEAD request (which basically asks the server not for the data itself, but for the headers only). you can look here.

查看更多
等我变得足够好
3楼-- · 2019-02-14 18:55

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.

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

Try this:

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

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

查看更多
Animai°情兽
4楼-- · 2019-02-14 18:58

i think your code already does that. you never call the read() method on the response, so you are never actually downloading the file's contents.

better yet... you could send an HTTP HEAD request using httplib instead of doing the HTTP GET that your urllib code does.

查看更多
登录 后发表回答