我正在尝试设置要在我的应用程序中使用的代理。当我尝试将其设置为系统属性时:
Proxy proxy = ... // code to retrieve proxy from .pac file
InetSocketAddress addr = (InetSocketAddress) proxy.address();
System.setProperty("java.net.useSystemProxies", "true");
System.setProperty("http.proxyHost", addr.getHostName());
System.setProperty("http.proxyPort", Integer.toString(addr.getPort()));
java.net.ConnectException: Connection timed out: connect
当我尝试连接到 URL 时它会抛出:
URL url = new URL(urlToConnect);
HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(); // Exception thrown in this line
但是,如果我将代理设置为参数openConnection()
:
HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection(proxy);
我的代码有效并且我能够连接到 URL,但是这个解决方案是不切实际的,因为我openConnection()
的代码中有很多。
将其用作系统属性时如何使其工作?