Search code examples
javajersey-2.0jersey-client

How can I use jersey-client with Apache httpclient underneath?


I am using jersey-client for a project and would like to make the Client use an HTTP client from the Apache httpclient librabry.

I have previously see this is possible.

I'm using Jersey 2.20.


Solution

  • Use ApacheConnectorProvider. Pass an instance to ClientConfig.connectorProvider() to get an instance of ClientConfig that will use an Apache HTTP client under the hood.

    Use the following dependency:

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

    Here's a working example:

    import javax.ws.rs.client.Client;
    import javax.ws.rs.client.ClientBuilder;
    
    import org.glassfish.jersey.apache.connector.ApacheConnectorProvider;
    import org.glassfish.jersey.client.ClientConfig;
    
    
    public class Test {
        @org.junit.Test
        public void test() {
            ClientConfig cc = new ClientConfig().connectorProvider(new ApacheConnectorProvider());
            Client client = ClientBuilder.newClient(cc);
            System.out.println(client.target("http://example.com/").request().get().getStatus());
        }
    }