How do I set the proxy for the JVM?

Many Java applications need Internet access, such as when reading an XML file that requires downloading its schema. Since I am behind a proxy server, how can I configure my JVM to use the java http.proxy settings to ensure proper connectivity?

The simplest way to set a proxy for your JVM is by passing system properties when running your Java application.

java -D http.proxyHost=proxy.example.com -Dhttp.proxyPort=8080 -D https.proxyHost=proxy.example.com -D https.proxyPort= 8443 -jar myApp.jar

:heavy_check_mark: Pros: Quick, no code changes required.

:x: Cons: Must be specified every time you run the application.

If you need to set the proxy dynamically within your Java code, you can use:

  • System.setProperty(“http.proxyHost”, “proxy.example.com”);
  • System.setProperty(“http.proxyPort”, “8080”);
  • System.setProperty(“https.proxyHost”, “proxy.example.com”);
  • System.setProperty(“https.proxyPort”, “8443”);

:heavy_check_mark: Pros: Works even if the app is launched without proxy settings.

:x: Cons: Requires modifying the application code.

If you need fine-grained control, such as bypassing the proxy for specific hosts, use Java’s Proxy class:

  • Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(“proxy.example.com”, 8080));
  • URL url = new URL(“http://example.com”);
  • HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);

:heavy_check_mark: Pros: Allows selective proxying (e.g., some connections can bypass the proxy).

:x: Cons: More complex, requires modifying the networking logic.