java每个线程都使用自己的代理
我正在尝试设置一个Java程序,其中每个线程都可以使用自己的代理
现在我只找到了一种全局设置代理的方法。(http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html)
As mentioned earlier, these settings affect all http connections during the entire lifetime of the VM invoked with these options. However it is possible, using the System.setProperty() method, to have a slightly more dynamic behavior.
Here is a code excerpt showing how this can be done:
//Set the http proxy to webcache.mydomain.com:8080
System.setProperty("http.proxyHost", "webcache.mydomain.com"); System.setPropery("http.proxyPort", "8080");
更新
我尝试使用proxy类,但当我不想使用所述代理时,无法创建直接连接:
private void setProxy()
{
if(proxyUrl != null)
{
SocketAddress addr = new InetSocketAddress(proxyUrl, proxyPort);
proxy = new Proxy(Proxy.Type.HTTP, addr);
}
else
{
proxy = new Proxy(Proxy.Type.DIRECT, null);
}
}
Exception in .... java.lang.IllegalArgumentException: type DIRECT is not compatible with address null
我怎样才能让这个直接连接工作?还没有试过代理
# 1 楼答案
Barry NL的解决方案是半有效的,因为我不知道如何在该解决方案中不使用代理
我想到的是:
proxyUrl
和proxyPort
在我的类的构造函数中如果我只设置了^{,我就无法调用
url.openConnection(proxy);
或者
proxy = new Proxy(Proxy.Type.DIRECT, null);
。 所以我写了我自己的openConnection
在建立任何连接之前必须调用
setProxy()
我也换了
与
# 2 楼答案
可以使用第3节中解释的Proxy类here:
你可以使用Proxy.NO_PROXY来:
这样做: