Tell Java Applications to Use macOS Automatic Proxy Configuration

Over the last few years, we’ve published a few posts about VPNs that build on each other. Each shows how to make day-to-day life a little nicer when you must connect to a Virtual Private Network (VPN) on macOS.

Based on what those posts cover, I have a LaunchAgent that ensures my automatic proxy configuration server is always running. I’m able to connect to a client VPN using openconnect and ocproxy, with only the traffic specified in the .pac file going through the VPN. Anything that’s not covered by the .pac configuration skips the VPN entirely — yay!

This works seamlessly for most applications (browsers, iOS simulators, Android Emulators, etc.). However, it doesn’t work for a Java application that needs to send traffic through the VPN proxy – unless you do some additional configuration.

Automatic Proxy Configuration

It turns out that Java has a specific command line option that tells it to use whatever proxy the OS has been configured to use.


  -Djava.net.useSystemProxies=true

A Specific Proxy

If you want to use another proxy besides the OS system proxy, that’s also possible using a different set of arguments.


  -DproxyHost=localhost -DproxyPort=3128

You could use this to point to a local proxy or potentially to a proxy running on a remote machine.

Running the Application

The Java application I needed was installed as a regular macOS .app application (in the /Applications directory). This means I’m not starting it using the java command from the command line. So how do you pass the application the flag telling it to use a proxy? With an environment variable!


  export JAVA_TOOL_OPTIONS='-Djava.net.useSystemProxies=true'

In macOS, there’s no place to set system-wide environment variables (unlike with Windows). So, the only decent option is to create a wrapper script that exports the variable and then opens the application.


#!/bin/bash

export JAVA_TOOL_OPTIONS='-Djava.net.useSystemProxies=true'

open /Applications/SomeJavaApp.app

Make that script executable (chmod +x ./wrapper.sh), run it, and the Java application will start up, and use the system proxy for just the .pac configured traffic.

Conversation

Join the conversation

Your email address will not be published. Required fields are marked *