Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can detect system Proxy Settings in Java application, but not in JUnit

  • Windows 7
  • Java 1.8.0_45
  • Eclipse Mars

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);
    }
}
like image 407
Ahmed Ashour Avatar asked Jun 29 '15 12:06

Ahmed Ashour


2 Answers

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>
like image 124
Tulio C Avatar answered Oct 14 '22 12:10

Tulio C


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.

like image 44
Brian Avatar answered Oct 14 '22 13:10

Brian