Thursday, April 3, 2008

Configuring HTTP Proxy in Java

Sometime ago I needed to configure a proxy for an example applications that has used both Axis, Axis2 and JAX-WS as SOAP Engines.

Usually to configure proxy you need to define the following system properties, when you start a JVM:
-Dhttp.proxySet=true -Dhttp.proxyHost=<host> -Dhttp.proxyPort=<port>

But unfortunately it doesn't always work. Actually it did work only for Axis.
So here are the solutions that worked:

In Axis2 it's possible to add the following code to the client that will copy proxy settings from system properties:
ServiceClient serviceClient = stub._getServiceClient();
Options options = serviceClient.getOptions();
if (System.getProperty("http.proxySet", "false").equals("true")) {
ProxyProperties proxyProperties = new ProxyProperties();
// set username and password if you need them
options.setProperty(HTTPConstants.PROXY, proxyProperties);

In JAX-WS you may set the proxy in the code:
if (System.getProperty("http.proxySet", "false").equals("true")) {
ProxySelector.setDefault(new ProxySelector() {

public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
throw new RuntimeException("Proxy connect failed", ioe);

public List select(URI uri) {
return Arrays.asList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort")))));

Recommended Reading

1. Effective Java (2nd Edition)
2. Java™ Puzzlers: Traps, Pitfalls, and Corner Cases
3. Mort

No comments: