How to add a http proxy for Jersey2 Client

An alternative without include jersey-apache-connector

public class Sample {

  public static void main(String[] args) {

    // you can skip AUTH filter if not required
    ClientConfig config = new ClientConfig(new SampleProxyAuthFilter());
    config.connectorProvider(
        new HttpUrlConnectorProvider().connectionFactory(new SampleConnectionFactory()));

    Client client = ClientBuilder.newClient(config);

    // there you go
  }
}

class SampleConnectionFactory implements HttpUrlConnectorProvider.ConnectionFactory {
  @Override
  public HttpURLConnection getConnection(URL url) throws IOException {
    return (HttpURLConnection) url
        .openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("host", 8080)));
  }
}

class SampleProxyAuthFilter implements ClientRequestFilter {

  @Override
  public void filter(ClientRequestContext requestContext) throws IOException {
    requestContext.getHeaders().add("Proxy-Authorization", "authentication");
  }
}

To set different proxy on runtime is not good solution. Accordingly, I used apache connector to do so:

add apache connector dependency defined:

<dependency>
 <groupId>org.glassfish.jersey.connectors</groupId>
 <artifactId>jersey-apache-connector</artifactId>
</dependency>

add apache connector to client

config.property(ApacheClientProperties.PROXY_URI, proxyUrl); 
Connector connector = new ApacheConnector(config); 
config.connector(connector); 

thanks @feuyeux, the solution is work for me, ps, the code below is works in the proxy with http basic auth:

    ClientConfig config = new ClientConfig();
    config.connectorProvider(new ApacheConnectorProvider());
    config.property(ClientProperties.PROXY_URI, proxy);
    config.property(ClientProperties.PROXY_USERNAME,user);
    config.property(ClientProperties.PROXY_PASSWORD,pass);
    Client client = JerseyClientBuilder.newClient(config);

hope to help others


If you use jersey 2.0 default http connector(which is JDK Http(s)URLConnection). You could just simple configure the proxy like:

    System.setProperty ("http.proxyHost", "proxy_server");
    System.setProperty ("http.proxyPort", "proxy_port");

For other implementations of http connector (Apache HTTP Client and Grizzly Asynchronous Client), I haven't tried before. But I think you could follow the instruction by http connector itself.