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

同一机器上urllib请求超时但Postman可正常请求的问题

问题:Python urllib请求超时但curl/Postman可正常运行

同一机器上,通过Postman发送POST请求可正常执行,对应的curl命令如下:

curl --location --request POST 'https://soar.xxx.com/acc_xxx_001/investigation/2009' \
--header 'Authorization: 12345' \
--header 'Content-Type: application/json' \
--data-raw '{"categories": ["chats"]}
'

但使用Python urllib发送相同请求时,出现超时错误,代码如下:

xsoar_api = 'https://soar.xxx.com/acc_xxx_001/investigation/2009'
req = urllib.request.Request(xsoar_api, method='POST')
req.add_header('Content-Type', 'application/json')
req.add_header('Authorization', '12345')
data = {"categories":["chats"]}
data = json.dumps(data)
data = data.encode()
with urllib.request.urlopen(req, data=data) as response:
    the_page = response.read()

报错信息:

urllib.error.URLError: <urlopen error [Errno 110] Operation timed out>

排查与解决建议

  • 代理配置差异:curl默认会读取系统代理配置,而urllib默认不会自动加载。可以尝试关闭代理测试:

    import urllib.request
    import json
    
    xsoar_api = 'https://soar.xxx.com/acc_xxx_001/investigation/2009'
    req = urllib.request.Request(xsoar_api, method='POST')
    req.add_header('Content-Type', 'application/json')
    req.add_header('Authorization', '12345')
    data = json.dumps({"categories":["chats"]}).encode()
    
    # 禁用代理
    proxy_handler = urllib.request.ProxyHandler({})
    opener = urllib.request.build_opener(proxy_handler)
    urllib.request.install_opener(opener)
    
    # 显式设置超时时间
    with urllib.request.urlopen(req, data=data, timeout=30) as response:
        the_page = response.read()
    
  • 显式设置超时参数:urllib的urlopen默认超时逻辑不明确,显式设置timeout参数(比如30秒),避免无限等待。

  • 重定向与SSL证书问题:

    • curl的--location会自动跟随重定向,urllib默认也支持,但可以显式指定redirect=True确认。
    • 若存在SSL证书验证问题,curl可能默认忽略,而urllib会严格验证。可临时关闭证书验证测试(生产环境不建议):
      import ssl
      ssl._create_default_https_context = ssl._create_unverified_context
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:51:31