我遇到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对我来说无法正常工作。
答案 0 :(得分:2)
来自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);
答案 1 :(得分:1)
System.getProperties().put(type + ".proxyUser", username);
System.getProperties().put(type + ".proxyPassword", password);
根据the official documentation,JRE并未承认其中任何一项。我相信Apache HTTP客户端可能会这样做,但不要引用我。
您需要安装java.net.Authenticator.