我收到urllib2.HTTPError:HTTP错误502:错误的网关

时间:2016-05-29 05:48:11

标签: python json url

/ *我得到urllib2.HTTPError:HTTP错误502:网关不好。* /

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

一周之前。我得到了结果。但现在我收到了错误。

任何人都可以解释一下我所遇到的阻碍情况,并请提供解决方案。

1 个答案:

答案 0 :(得分:3)

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供应商往往对服务质量非常苛刻,如果他们发现有人遇到问题可能会很快提供帮助。