【问题标题】:Python requests through VPN giving 502 Bad Gateway通过 VPN 发出的 Python 请求给出 502 Bad Gateway
【发布时间】:2026-01-08 09:45:02
【问题描述】:

我正在尝试使用requests 库从我公司网络内的服务器获取一些数据。我正在使用 VPN 进入我公司的网络,并且还设置了公司代理。我尝试访问的地址仅在该公司网络中可见。

import requests

url = "http://some.private.server.net"

r = requests.get(url)

我的环境中同时设置了 HTTP_PROXY 和 HTTPS_PROXY。我正在运行 Windows 7。

我从这段代码中得到错误 502。当我物理连接到公司网络时它起作用了,所以我认为问题在于通过 VPN 而不是代理连接。我可以使用我的网络浏览器访问该地址。

我不太了解网络,但我尝试将请求的源地址更改为 VPN 网络适配器使用的 IP 地址。

import requests
from requests_toolbelt.adapters.source import SourceAddressAdapter

s = requests.Session()
ip = "y.y.y.y"
s.mount('http://', SourceAddressAdapter(ip))
s.mount('https://', SourceAddressAdapter(ip))

url = "http://some.private.server.net"

response = s.get(url)

这仍然导致与上述相同的错误 (502)。

编辑:仔细查看 502 错误,代理服务器正在返回消息“您正在查找的页面的主机名不存在”。

因此,我尝试将 URL 替换为我尝试访问的服务器的 IP 地址,但由于“网关超时”而得到 502。

我可以从命令行 ping 该 IP 没有问题。

【问题讨论】:

    标签: python python-3.x python-requests vpn http-proxy


    【解决方案1】:

    具有讽刺意味的是,我不需要使用代理来访问此服务器。你可以这样做,

    import requests
    
    s = requests.Session()
    s.trust_env = False
    
    url = "http://some.private.server.net"
    
    response = s.get(url)
    

    【讨论】:

    • 谢谢,这正是我今天早上所需要的。很多人在找到正确答案后都不愿意发布正确的答案,干得好。
    • 我使用这个时连接被拒绝
    • 我在添加之前遇到了同样的问题。
    最近更新 更多