Python 请求:urllib3.exceptions.ProtocolError:'连接中止。'
Posted
技术标签:
【中文标题】Python 请求:urllib3.exceptions.ProtocolError:\'连接中止。\'【英文标题】:Python Requests : urllib3.exceptions.ProtocolError: 'Connection aborted.'Python 请求:urllib3.exceptions.ProtocolError:'连接中止。' 【发布时间】:2022-01-22 15:32:53 【问题描述】:我是 python 的新手。我正在尝试从 API 中提取数据。我尝试使用邮递员在本地提取数据并提取数据。但是当我使用 python 请求时,我收到连接中止错误。有人可以帮助我理解这个问题。
以下是我尝试过的代码:
import requests
from requests import request
url = "https://abcd/smart_general_codes?category=BANK"
payload=
headers =
'TenantId': 'IN0XXX',
'Accept-Language': 'en_us',
'Transfer-Encoding': 'chunked',
'fileType': 'json',
'Authorization': 'Basic XXXXXXXXXX'
response = requests.get(url, headers=headers, data=payload, verify=False)
print(response.status_code)
print(response.text)
代码2:
import http.client
conn = http.client.HTTPSConnection("main.com")
payload = ''
headers =
'powerpayTenantId': 'IN0XXX',
'Accept-Language': 'en_us',
'Transfer-Encoding': 'chunked',
'fileType': 'json',
'Authorization': 'Basic XXXXXXXXXX'
conn.request("GET", "abcd/smart_general_codes?category=BANK", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
使用 httpclient 和 requests 方法都会抛出以下错误:
urllib3.exceptions.ProtocolError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "login_2.py", line 20, in <module>
response = requests.get(url, headers=headers, data=payload, verify=False)
File "/usr/lib/python3/dist-packages/requests/api.py", line 72, in get
return request('get', url, params=params, **kwargs)
File "/usr/lib/python3/dist-packages/requests/api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 520, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 630, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python3/dist-packages/requests/adapters.py", line 490, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))
【问题讨论】:
【参考方案1】:尝试在如下标头中添加虚假的用户代理(例如 chrome)和您的 cookie(如果需要):
headers =
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (Khtml, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
'cookie': '<Your cookie>'
顺便说一句,您可以通过在浏览器的开发者控制台中输入 document.cookie
来获取您的 cookie。
【讨论】:
感谢@AgOH 的回复。但是上面的东西仍然没有解决我的问题。【参考方案2】:我已经解决了这个问题。在邮递员中,接受语言显示为 en_us,但将其更新为 en_US 有效。
【讨论】:
以上是关于Python 请求:urllib3.exceptions.ProtocolError:'连接中止。'的主要内容,如果未能解决你的问题,请参考以下文章