2009-12-11 94 views
2

我正在使用我发布文件的API。但是,当我收到响应时,HTTP状态代码是202.这是可以预料的,但此外API还会响应XML内容。响应代码202,不是合格的错误代码

所以在我的尝试/除了块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和保持响应内容,但不会引发错误?

回答

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()等来检查响应的其他方面。

+0

纠正我,如果我错了,但我不能使用HTTPConnection的urllib2.Request类。 – 2009-12-11 19:41:12

+0

你确实是对的。您正在使用的请求类中是否有特定的东西? – 2009-12-11 19:47:04

+0

是,字节字符串,或者更准确地说是一个zip文件。 – 2009-12-11 20:14:31