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

为何Python的httpx.get/requests.get调用该API远慢于cURL?

Python HTTP库调用API慢于cURL/浏览器的原因分析

核心原因拆解

  • HTTP协议与连接优化差异
    requests默认使用HTTP/1.1,在TCP连接复用、握手流程上的优化远不如cURL和现代浏览器。httpx虽开启了HTTP/2,但默认配置下的协议协商、多路复用效率仍不及cURL——后者默认支持HTTP/2甚至HTTP/3,能大幅减少连接建立的开销。

  • 请求头模拟度不足
    cURL和浏览器会自动携带贴近真实用户的请求头(如User-Agent、Accept、Accept-Encoding等),而requests/httpx的默认请求头带有明显Python标识(比如python-requests/2.31.0),容易被API的反爬机制识别为非合法客户端,触发限速或延迟响应逻辑。

  • DNS与连接池策略差异
    浏览器和cURL通常内置DNS缓存,可跳过重复解析步骤;而Python HTTP库默认可能每次请求都重新解析DNS,加上TCP握手时间,累积导致延迟。此外,cURL默认启用TCP Fast Open等优化,进一步缩短连接建立时间,而Python库大多默认未开启这类配置。

验证与优化示例

修改请求头模拟浏览器,可显著提升请求速度:

requests优化示例

import requests
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
    'Accept': 'application/json, text/plain, */*',
    'Accept-Encoding': 'gzip, deflate, br'
}
response = requests.get('https://v6.db.transport.rest/stations?query=berlin', headers=headers)
print(response.text)

httpx优化示例

import httpx
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
    'Accept': 'application/json, text/plain, */*',
    'Accept-Encoding': 'gzip, deflate, br'
}
client = httpx.Client(http2=True, headers=headers)
response = client.get('https://v6.db.transport.rest/stations?query=berlin')
print(response.text)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 07:33:24