Archive for March, 2011

Writing powerful REST Client using the AsyncHttpClient Library and Jersey

The Jersey Client Framework is a powerful library that easily allow the writing of client based REST client.  Recently I’ve implemented a new transport for the framework based on the AsyncHttpClient library. You can now get the best of both worlds: an easy REST Client API powered by a poweful http client library.

Currently the Jersey Client Framework ships with two transport, one based on the infamous URLConnection, and one based on Apache Http Client.  Recently I needed to replace Wink with Jersey in one of my Sonatype project (guess one?) and  at the same time realized the Jersey Client features was quite limited in terms of what you can do and what is exposed to the client. I understand the original design was to abstract the underlying transport, but unfortunately all http library aren’t supporting the same set of features. Now if you are familiar with the Jersey client, creating a resource is as simple as (see here for the complete tutorial):

    Client c = Client.create(); 

Now if you want to customize the client a little, you can do (complete info here):

    ClientConfig cc = new DefaultClientConfig();
        ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
    Client c = Client.create(cc); 

Next step is as simple as:

     WebResource r = c.resource(“http://localhost:8080/xyz”);
     ClientResponse response = r.get(ClientResponse.class);
     EntityTag e = response.getEntityTag();
     String entity = response.getEntity(String.class);

Very simple. Now in order to take advantage of AHC (AsyncHttpClient) features, all you need to do is to first get the library from here, and then just do get a reference to the AsyncHttpClient’s Config class (if you aren’t familiar with AHC, take a look at this introduction)

     DefaultAhcConfig config = new DefaultAhcConfig();
           new Realm.RealmBuilder()
     Client c = Client.create(config);
     WebResource r = c.resource(getUri().build());

You just added Kerberos support to Jersey Client! The trick here consists of getting a reference to the AsyncHttpClientConfig and configure all the cool stuff offered by AHC. As an example, you can add resumable support, Request/Response or IOException Filter by just doing:

        .addIOExceptionFilter(new ResumableIOExceptionFilter());

For any questions, use Twitter to reach me! You can checkout the code on Github, download the jars from Maven Central or use Maven:


Categories: Async Http client