Requests报”requests.exceptions.ChunkedEncodingError: (“Connection broken: {error message}”, ConnectionResetError(104, ‘Connection reset by peer’)) “的原因以及解决办法

  • Post category:Python

这个错误通常出现在使用requests库时,对一个返回内容编码为chunked的响应进行解析时。它意味着在解码响应内容的过程中发生了错误,可能是因为连接已被重置或由于其他原因导致连接意外关闭。

这种错误的解决方法可以包括以下几个方面:

  1. 不使用chunked编码格式: 可以尝试设置requests的stream参数为False来关闭chunked编码。例如,使用以下命令发送请求:
response = requests.get(url, stream=False)
  1. 重试连接: 由于这种错误可能是由于连接超时或网络问题等原因引起的,因此可以尝试通过延迟或进行多次连接来解决该问题。可以使用如下命令设置连接超时时间并重试连接:
import requests
from requests.adapters import HTTPAdapter
from requests.exceptions import ChunkedEncodingError
import time

s = requests.Session()
s.mount('http://', HTTPAdapter(max_retries=3))
s.mount('https://', HTTPAdapter(max_retries=3))

url = 'http://example.com/'
while True:
    try:
        response = s.get(url, timeout=5)
        break
    except ChunkedEncodingError:
        time.sleep(5)
        continue
  1. 升级requests库版本: 如果你使用的requests库版本比较低,可能会遇到这个问题。可以尝试升级到最新版本,以便获得更好的稳定性和错误解决方案。

总的来说,这个错误可以通过多个方法来解决,具体的解决方案要视情况而定。可以根据错误提示信息,结合自己的代码调试出最适合自己的解决方案。