如何使用 urlib2 访问错误的响应标头?
我正在使用 Harvest API (http://www.getharvest.com/api)。当客户端超过其配额时,将返回 503 响应。在该响应中应该有一个名为“Retry-After”的标头,告诉我在重试之前需要等待多长时间。
调用失败时如何访问响应标头?我正在捕获 HTTPError 异常,但不知道如何从中获取标头。
我可以使用 exception.read() 获取响应主体,但这只是没有标头的主体。
一些相关代码:
try:
request = urllib2.Request( url=self.uri+url, headers=self.headers )
r = urllib2.urlopen(request)
xml = r.read()
return parseString( xml )
except urllib2.HTTPError as err:
logger.debug("EXCEPTION: %s" % err.read() )
I'm using the Harvest API (http://www.getharvest.com/api). When a client goes over it's quota, a 503 response is returned. In that response there should be a header called "Retry-After" that tells me how long to wait before trying again.
How do I access the response headers when the call fails? I'm grabbing the HTTPError exception, but can't figure out how to get the headers out of it.
I can get the response body with exception.read(), but that's just the body without headers.
Some relevant code:
try:
request = urllib2.Request( url=self.uri+url, headers=self.headers )
r = urllib2.urlopen(request)
xml = r.read()
return parseString( xml )
except urllib2.HTTPError as err:
logger.debug("EXCEPTION: %s" % err.read() )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
它是一本字典,因此使用 err.headers['Retry-After']
Try this:
It's a dictionary, thus use
err.headers['Retry-After']
所有相关的响应信息都可以从捕获的异常中获得。
All related response information are available from the caught exception.
err.read() 返回正文,err.info() 返回标头
err.read() returns body, and err.info() returns headers