概述:我使用urllib2和json库调用python2.7的API。当我运行脚本时,如果结果计数高于20,我会收到以下错误:
错误:[Errno 10054]现有连接被强行关闭 远程主机
脚本:
import json
import urllib2
import webbrowser
url = "http://poi.????.com:xxxx/k/search?name==smith&limit==30"
response = urllib2.urlopen(url)
webbrowser.open(url)
data = json.load(response)
count = "count = "+str(data['count'])
print count
for i in data['results']:
name = i['name']
print name
预期结果:我运行脚本,API以“200 OK”状态响应,我的webbrowser.open(url)行在我的浏览器中打开响应。我的IDLE shell打印输出。
问题:当我在API中使用limit参数并将其设置为< 20时,它会在我的IDLE shell中按预期响应。但是,如果我设置限制> 20或者没有设置限制,我仍然得到200 OK响应,浏览器填充结果但我的IDLE shell产生'连接被强制关闭'错误。
软件:我在Windows 7/8和Ubuntu 14.04上试过这个。在家里通过VPN和在有线网络上工作。
IDLE的追踪电话:
Traceback (most recent call last):
File "C:\Users\xxx\userQueryService.py", line 9, in <module>
data = json.load(response)
File "C:\Python27\lib\json\__init__.py", line 286, in load
return loads(fp.read(),
File "C:\Python27\lib\socket.py", line 351, in read
data = self._sock.recv(rbufsize)
File "C:\Python27\lib\httplib.py", line 573, in read
s = self.fp.read(amt)
File "C:\Python27\lib\socket.py", line 380, in read
data = self._sock.recv(left)
error: [Errno 10054] An existing connection was forcibly closed by the remote host
Ubuntu python shell中的回溯调用:
>>> data = json.load(response)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/json/__init__.py", line 290, in load
**kw)
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Unterminated string starting at: line 1 column 43303 (char 43302)
答案 0 :(得分:0)
我设法通过使用请求库而不是 urllib2 和 json 来解决我的问题。我为那些有类似问题的人提供了我的代码(注意我还包括一个异常处理程序):
import webbrowser
import requests
url = "http://poi.????.com:xxxx/k/search?name==smith&limit==30"
r = requests.get(url)
try:
data = r.json()
webbrowser.open(url)
count = "count = "+str(data['count'])
print count
for i in data['results']:
name = i['name']
print name
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)