Python JSON load leads to Error: Connection Forcibly Closed

Python JSON load leads to Error: Connection Forcibly Closed

概述:我正在使用 urllib2 和 json 库调用带有 python2.7 的 API。当我 运行 脚本时,如果结果计数高于 20,我会收到以下错误:

error: [Errno 10054] An existing connection was forcibly closed by the remote host

脚本:

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 中使用限制参数并将其设置为 <20 时,它会按我的 IDLE shell 中的预期进行响应。但是,如果我设置限制 > 20 或不设置限制,我仍然会收到 200 OK 响应,浏览器会填充结果,但我的 IDLE shell 会产生 'connection was forcibly closed' 错误。

软件:我已经在 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

Ubuntupythonshell:

中的回溯调用
>>> 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)

我设法通过使用 requests 库而不是 urllib2json 来解决我的问题。我已经为那些有类似问题的人提供了我的代码(注意我还包括了一个异常处理程序):

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)