Have you ever spent hours lovingly coding your Next Great Program, only to discover that part of your audience cannot use it because they are behind a proxy server? If you are going to be using the network, it pays to plan ahead for this situation. Adding proxy capability to your program is not very difficult. Here’s a quick code snippet that does just that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static void enableProxy(String host, int port, final String username, final char[] password) {
    System.setProperty("http.proxyHost", host);
    System.setProperty("http.proxyPort", String.valueOf(port));

    if (username != null && !username.isEmpty()) {
        Authenticator.setDefault(new Authenticator() {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }

        });
    }
}

Calling this method with a host and port will set up the system properties necessary for proxy access to work. If the username is not null, it will also set up a PasswordAuthentication object to perform authentication as needed. To disable the proxy, call this method:

1
2
3
4
public static void clearProxy() {
    System.clearProperty("http.proxyHost");
    System.clearProperty("http.proxyPort");
}

Now, all you have to do is provide a way for the user to enter the proxy settings, persist the settings, and call the enableProxy method. At application startup, you can read the settings from where you have stored them and enable the proxy.

Another option is to tell the JVM to use your system proxy settings. However, I have had problems with this detecting the system properties in some cases on some operating systems:

1
System.setProperty("java.net.useSystemProxies", "true");

Adding proxy support to your code is easy! Taking the time to add proxy support to your application will save you headaches later on down the road. Happy coding!