响应代码202,非合格错误代码

2 投票
1 回答
1995 浏览
提问于 2025-04-15 16:56

我正在使用一个可以上传文件的API。不过,当我收到响应时,HTTP状态码是202。这是正常的,但这个API还会返回一些XML内容。

所以在我的try/except代码块中,使用urllib2.urlopen会导致抛出一个urllib2.HTTPError,这样就会丢失XML内容。

try:
    response = urllib2.urlopen(req)
except urllib2.HTTPError, http_e:
    if http_e.code == 202:
        print 'accepted!'
        pass

print response.read() # UnboundLocalError: local variable 'response' referenced before assignment

我该怎么做才能在预期得到202状态码的同时,保留响应内容,而不抛出错误呢?

1 个回答

4

编辑

我真是傻,居然忘了查看urllib2返回的异常信息。这个异常包含了我之前提到的httplib的所有属性。这样做应该能解决你的问题:

try:
    urllib2.urlopen(req)
except urllib2.HTTPError, e:
    print "Response code",e.code # prints 404
    print "Response body",e.read() # prints the body of the response...
                                   # ie: your XML
    print "Headers",e.headers.headers

原文

在这种情况下,由于你使用的是HTTP作为传输协议,使用httplib库可能会更有效:

>>> import httplib
>>> conn = httplib.HTTPConnection("www.stackoverflow.com")
>>> conn.request("GET", "/dlkfjadslkfjdslkfjd.html")
>>> r = conn.getresponse()
>>> r.status
301
>>> r.reason
'Moved Permanently'
>>> r.read()
'<head><title>Document Moved</title></head>\n<body><h1>Object Moved</h1>
 This document may be found   
 <a HREF="http://stackoverflow.com/dlkfjadslkfjdslkfjd.html">here</a></body>'

你还可以使用r.getheaders()等方法来查看响应的其他方面。

撰写回答