Java and proxies

Proxy management is an issue what we must manage in almost all projects. This article show how to configure proxy management into Java Application and into Apache Tomcat

Java Application

The proxy properties must be passed to the JVM by the following parameters :

    http.proxyHost  # define the proxy's host
    http.proxyPort #  define the proxy's port.The default value is 80.
    http.nonProxyHosts # define the host which are not take into account by the proxy. The default value is  localhost|127.*|[::1]

For https, the parameters are https.proxyHost and https.proxyPort

For authenticated proxies, you must add something. We can think that some parameters like http.proxyUser and http.proxyPassword exist. But it does not.

In fact, a java.net.Authenticator instance is needed. In the initialisation of the application, the following code must be executed :

    Authenticator.setDefault(new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(authUser, authPassword.toCharArray());
        }
    });

The authUser and authPassword can be passed to this code by custom jvm parameters like http.proxyUser and http.proxyPassword.

Example :

    java -Dhttp.proxyHost=proxy.enterprise.fr -Dhttp.proxyPort=3128 -Dhttp.proxyUser=user1 -Dhttp.proxyPassword=password1 -jar example.jar

Since JDK 1.8_u111, the Basic authentication scheme has been deactivated. If required, this authentication scheme can be reactivated by removing Basic from the jdk.http.auth.tunneling.disabledSchemes networking property, or by setting a system property of the same name to "" ( empty ) on the command line. For more information, see http://www.oracle.com/technetwork/java/javase/8u111-relnotes-3124969.html Apache Tomcat

In the previous part, we have seen that the proxy parameters are passed to the JVM. Therefore, for Apache Tomcat, these parameters must be passed to the JVM also.

In Tomcat, the JVM parameters are filled by a setenv.sh file into the bin directory. The setenv.sh looks like :

    #! /bin/sh

    export JAVA_OPTS="$JAVA_OPTS -Dhttp.proxyHost=proxy.enterprise.fr"
    export JAVA_OPTS="$JAVA_OPTS -Dhttp.proxyPort=3128"
    export JAVA_OPTS="$JAVA_OPTS -Dhttp.proxyUser=user1"
    export JAVA_OPTS="$JAVA_OPTS -Dhttp.proxyPassword=password1"

Next Post