如何在 (py)curl 中获取 HTTP 状态消息?
花了一些时间研究 pycurl 和 libcurl 文档,我仍然找不到一种(简单)方法,如何在 pycurl 中获取 HTTP 状态消息(原因短语)。
状态码很简单:
import pycurl
import cStringIO
curl = pycurl.Curl()
buff = cStringIO.StringIO()
curl.setopt(pycurl.URL, 'http://example.org')
curl.setopt(pycurl.WRITEFUNCTION, buff.write)
curl.perform()
print "status code: %s" % curl.getinfo(pycurl.HTTP_CODE)
# -> 200
# print "status message: %s" % ???
# -> "OK"
spending some time studying pycurl and libcurl documentation, i still can't find a (simple) way, how to get HTTP status message (reason-phrase) in pycurl.
status code is easy:
import pycurl
import cStringIO
curl = pycurl.Curl()
buff = cStringIO.StringIO()
curl.setopt(pycurl.URL, 'http://example.org')
curl.setopt(pycurl.WRITEFUNCTION, buff.write)
curl.perform()
print "status code: %s" % curl.getinfo(pycurl.HTTP_CODE)
# -> 200
# print "status message: %s" % ???
# -> "OK"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我自己找到了一个解决方案,它可以满足我的需要,但可能更强大(适用于 HTTP)。
它基于这样一个事实:通过 pycurl.HEADERFUNCTION 获取的捕获标头包含状态行。
i've found a solution myself, which does what i need, but could be more robust (works for HTTP).
it's based on a fact that captured headers obtained by
pycurl.HEADERFUNCTION
include the status line.这是一个旧线程,但我来这里寻找类似的信息。如果它只是您要查找的状态代码,例如 200、404、500 等,那么只需执行:
your_curl_handle.getinfo(pycurl.RESPONSE_CODE)
,它应该返回一个数字状态代码:)
This is an old thread but I got here looking for similar information. If it is just the status code you're looking for, such as 200, 404, 500 etc. then just do:
your_curl_handle.getinfo(pycurl.RESPONSE_CODE)
which should return a numerical status code :)
我认为您可以使用 human_curl 库来创建简单的代码。
有关 human_curl 的完整文档,您可以在 https://github.com/Lispython/ human_curl 上获取
I think that you can use human_curl library to create you code simple.
Full documentation on human_curl you can get on https://github.com/Lispython/human_curl
如果您只想要代码,则可以这样做,并假设您的
pycurl.Curl()
实例名为curl
(即curl = pycurl.Curl()
),你可以这样做,但在我看来,最好的方法是自己解析标头,而不是让库给你提供一切。
If you only want the code, you can do, and assuming your
pycurl.Curl()
instance is calledcurl
(ie.curl = pycurl.Curl()
), you can doBut the nice way in my opinion is to parse the header yourself instead of letting libraries spoon-feed you everything.
尝试 BaseHTTPServer.BaseHTTPRequestHandler.responses,它应该包含一个错误代码字典,如 此页面中所述。
希望这有帮助。
Try BaseHTTPServer.BaseHTTPRequestHandler.responses, it should contain an errorcode dictionnary as explained in this page.
hope this helps.