gpt4 book ai didi

java - URLConnection 不使用代理设置

转载 作者:行者123 更新时间:2023-11-29 05:38:37 31 4
gpt4 key购买 nike

HttpsURLConnection 有问题 - 未使用代理。
这是代码:

//proxy
String type = "https";
System.getProperties().put(type + ".proxyHost", host);
System.getProperties().put(type + ".proxyPort", port);
System.getProperties().put(type + ".proxyUser", username);
System.getProperties().put(type + ".proxyPassword", password);

/*some SSL stuff*/

//connection
URL url = new URL(url0);
URLConnection urlConnection = url.openConnection();
urlConnection.setUseCaches(false);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(false);
urlConnection.setRequestProperty("Connection", "Keep-Alive");

HttpsURLConnection httpConn = (HttpsURLConnection)urlConnection;
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestProperty("Proxy-Authorization", "Basic " + Base64Converter.encode(username + ":" + password));
httpConn.connect();

连接忽略所有代理设置,httpConn.usingProxy()false
我还尝试将 Proxy 实例传递给 url.openConnection() 并将代理登录/密码设置为默认 Authenticator。在那种情况下,连接使用了代理,但我得到了 407,因此 Authenticator 似乎无法正常工作。

最佳答案

来自 How do I make HttpURLConnection use a proxy? :

从 java 1.5 开始,您还可以将 java.net.Proxy 实例传递给 openConnection() 方法:

//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);

如果您的代理需要身份验证,它会给您响应 407。

在这种情况下,您需要以下代码:

Authenticator authenticator = new Authenticator() {

public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("user",
"password".toCharArray()));
}
};
Authenticator.setDefault(authenticator);

关于java - URLConnection 不使用代理设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18567663/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com