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
Pros: Quick, no code changes required.
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”);
Pros: Works even if the app is launched without proxy settings.
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);
Pros: Allows selective proxying (e.g., some connections can bypass the proxy).
Cons: More complex, requires modifying the networking logic.