You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

aiohttp代理问题:GET请求IP可轮换,其他请求为何无法轮换?

aiohttp POST/PUT/PATCH请求代理IP无法轮换的解决方法

使用aiohttp发起GET请求时,配置的SmartProxy代理能正常轮换IP,但POST、PUT、PATCH等请求每次都固定使用同一个IP。目前只能通过每次请求重建ClientSession解决,但频繁创建会话耗时严重。

可正常轮换IP的GET请求代码:

resp = await session.request('GET', url='https://httpbin.org/get', proxy=Proxy.LIST, headers=headers, **kwargs)
resp.raise_for_status()
data = await resp.json()
print(data)

无法轮换IP的POST请求代码:

resp = await session.request('POST', url='https://httpbin.org/post', proxy=Proxy.LIST, headers=headers, **kwargs)
resp.raise_for_status()
data = await resp.json()
print(data)

问题原因

aiohttp的ClientSession默认会复用TCP连接,而SmartProxy这类代理是在连接建立阶段分配IP。对于POST等请求,服务器通常返回Connection: keep-alive头,导致aiohttp复用已建立的连接,后续请求都会使用同一个代理IP;而GET请求可能因服务器返回Connection: close或其他原因,连接未被复用,每次请求都会新建连接,从而触发代理IP轮换。

解决方案

不需要每次重建ClientSession,通过以下两种方式强制每次请求新建连接即可:

方法1:请求时添加Connection: close头

在POST/PUT/PATCH请求的headers中加入Connection: close,强制请求结束后关闭连接,下次请求会重新建立连接并获取新IP:

# 修改headers,添加强制关闭连接的配置
headers.update({'Connection': 'close'})
resp = await session.request('POST', url='https://httpbin.org/post', proxy=Proxy.LIST, headers=headers, **kwargs)
resp.raise_for_status()
data = await resp.json()
print(data)

方法2:配置ClientSession的Connector强制关闭连接

初始化ClientSession时使用TCPConnector并设置force_close=True,这样所有请求结束后都会关闭连接,自动触发IP轮换:

import aiohttp

# 初始化带强制关闭连接的Session
connector = aiohttp.TCPConnector(force_close=True)
async with aiohttp.ClientSession(connector=connector) as session:
    # 发起POST请求,无需额外修改headers
    resp = await session.request('POST', url='https://httpbin.org/post', proxy=Proxy.LIST, headers=headers, **kwargs)
    resp.raise_for_status()
    data = await resp.json()
    print(data)

注意事项

  • 方法2会影响所有请求的连接复用,若部分请求需要保持长连接,可针对特定请求使用方法1单独设置。
  • SmartProxy的单入口地址确实支持每次连接轮换IP,核心是确保每次请求都新建与代理的TCP连接。

内容的提问来源于stack exchange,提问作者exerte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 15:52:38