If you have system proxy set up to HTTP, the below will print HTTP
only if it runs from main
method of java application.
However, if it is called from JUnit 4 test (in eclipse), it always prints DIRECT
.
It is also noted that defining -Djava.net.useSystemProxies=true
in eclipse: Run configurations -> Arguments -> VM arguments. The test simply hangs.
Any idea what is going on?
Thanks a lot,
public void printSystemProxy() {
System.setProperty("java.net.useSystemProxies", "true");
try {
final List<Proxy> list = ProxySelector.getDefault().select(new URI("http://foo/bar"));
for (final Proxy proxy : list) {
System.out.println(proxy.type());
}
}
catch (final URISyntaxException e) {
throw new IllegalStateException(e);
}
}
try making a TestRunner configuration (right-click/RunAs...) with the following VM parameters:
-Dhttp.proxyHost=<YOUR_PROXY>
-Dhttp.proxyPort=<YOUR_PORT>
-Dhttp.nonProxyHosts=<IF YOU NEED THIS (pipe as separator)>
-Dhttp.proxyUser=<YOUR_NAME>
-Dhttp.proxyPassword=<YOUR_PASWORD>
You can't change Java's system proxy behavior on runtime. The java.net.useSystemProxies
system property is only read on start-up. From the documentation (emphasis added):
java.net.useSystemProxies (default: false)
On recent Windows systems and on Gnome 2.x systems it is possible to tell the java.net stack, setting this property to true, to use the system proxy settings (both these systems let you set proxies globally through their user interface). Note that this property is checked only once at startup.
Setting the system property on the fly won't change the behavior. You have to send it in as a JVM argument using -D
like you're doing with your main
method. An alternative would be to not use the system proxies and instead allow the user to supply their own.
Alternatively, the other proxy properties like http.proxyHost
, http.proxyPort
, etc. (listed on the documentation link above) can be modified after the application has been started. Depending on your application, this may be a better solution anyway since it will generally have better cross-platform support.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With