如何让 HttpURLConnection 使用代理? [英] How do I make HttpURLConnection use a proxy?
本文介绍了如何让 HttpURLConnection 使用代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我这样做...
conn = new URL(urlString).openConnection();
System.out.println("Proxy? " + conn.usingProxy());
打印
Proxy? false
问题是,我支持代理.在 Windows 上,JVM 从哪里获取其代理信息?我该如何设置?我的所有其他应用似乎都对我的代理非常满意.
The problem is, I am behind a proxy. Where does the JVM get its proxy information from on Windows? How do I set this up? All my other apps seem perfectly happy with my proxy.
推荐答案
从 java 1.5 开始,您还可以通过 java.net.Proxy 实例到 openConnection(proxy)
方法:
Since java 1.5 you can also pass a java.net.Proxy instance to the openConnection(proxy)
method:
//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.
If your proxy requires authentication it will give you response 407.
在这种情况下,您将需要以下代码:
In this case you'll need the following code:
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("user",
"password".toCharArray()));
}
};
Authenticator.setDefault(authenticator);
这篇关于如何让 HttpURLConnection 使用代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文