在python中使用HTTPS代理发出请求

2024-05-16 02:33:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我的VPN提供商(NordVP)刚刚关闭了其代理服务器上的所有HTTP端口。我可以用cURL确认HTTPS端口工作正常,例如,以下工作正常:

curl -x https://proxy_server:89 --proxy-user username:password -L url

虽然这刚刚停止工作:

curl -x http://proxy_server:80 --proxy-user username:password -L url

两天前它还可以用。在python中,我试图使用request模块发出HTTP请求:

import requests
proxies = {
  "https":"https://user:password@proxy_server:port"
}

response = requests.get("https://api64.ipify.org?format=json", proxies=proxies)
print(response.text)

但我有以下3个错误:

ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

During handling of the above exception, another exception occurred:

...

MaxRetryError: HTTPSConnectionPool(host='api64.ipify.org', port=443): Max retries exceeded with url: /?format=json (Caused by ProxyError('Cannot connect to proxy.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)))

During handling of the above exception, another exception occurred:

...

ProxyError: HTTPSConnectionPool(host='api64.ipify.org', port=443): Max retries exceeded with url: /?format=json (Caused by ProxyError('Cannot connect to proxy.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None)))

我看到关于这个主题有一个非常古老的问题,但它似乎不再相关了


Tags: thehttpsnonehosturlbyserverport
1条回答
网友
1楼 · 发布于 2024-05-16 02:33:59

以下是一个解决方法:

Authenticator proxyAuthenticator = new Authenticator() {
    @Override public Request authenticate(Route route, Response response) throws IOException {
        String credential = Credentials.basic(username, password);
        return response.request().newBuilder().header("Proxy-Authorization", credential).build();
    }
};

OkHttpClient client = new OkHttpClient.Builder()
        .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)))
        .proxyAuthenticator(proxyAuthenticator);
        .socketFactory(new DelegatingSocketFactory(SSLSocketFactory.getDefault()))
        .build();

在Android上,将以下内容添加到gradle中:

implementation 'org.conscrypt:conscrypt-android:2.5.0'

这是你的应用程序onCreate()

Security.insertProviderAt(Conscrypt.newProvider(), 1);

https://github.com/square/okhttp/issues/6561

相关问题 更多 >