/* Iam getting urllib2.HTTPError: HTTP Error 502: Bad Gateway.*/
import urllib2
import json
# locu_api = 'd1dab0b393b10f56532cacf6835d2619973f5f46'
url = 'http://cricapi.com/api/cricketNews'
/*The above url is used from cricapi.com*/
str = ""
json_obj = urllib2.urlopen(url)
data = json.load(json_obj)
i = 0
titles = {}
for item in data['data']:
if item:
titles[i] = item['title']
i+=1
print titles
/*printing all the content fetched from cricapi*/
if not str:
print "Hello"
构建完上面的代码后, 我收到以下错误:
追溯(最近的调用最后):
File "/home/karthi/Desktop/proj/cric.py", line 51, in <module>
json_obj = urllib2.urlopen(url).read()
File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 410, in open
response = meth(req, response)
File "/usr/lib/python2.7/urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python2.7/urllib2.py", line 448, in error
return self._call_chain(*args)
File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 502: Bad Gateway
一周前。我能够得到结果。但现在我收到了错误。
任何人都可以解释一下我遇到的障碍并提供解决方案。
最佳答案
Karthi,您提出的问题对于许多 API 提供商来说很常见。发生的情况是,如果服务器负载在那一瞬间超出容量,您可能会从反向代理收到 502,从而遇到错误情况。
解决此问题的推荐方法是进行重试计数。例如
function fetchdata(url) {
try {
// hit the URL and fetch data
} catch() {
// retry in case of an error
return fetchdata(url);
}
}
如果您使用支持回调的语言,另一种方法是重试给定次数,然后调用回调
function fetchdata(url, callback) {
try {
// hit the URL and fetch data
// success!
callback(returndata);
} catch() {
// retry in case of an error
if(exceeded retry count) callback(error);
else
fetchdata(url, callback);
}
}
注意:这是示例伪代码,不是正确可用的代码,所以请这样对待它
自然,唯一的长期解决方法是与 API 提供商联系并请求他们帮助找出问题所在。大多数 API 提供商往往对服务质量相当关注,如果他们看到有人面临问题,可能会迅速提供帮助。
关于python - 我收到 urllib2.HTTPError : HTTP Error 502: Bad Gateway,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37506648/