Introducing Ning’s Asynchronous Http Client library.

On March 3, 2010, Ning released a new Asynchronous HTTP Client library as open source. Its purpose is to allow Java applications to easily execute HTTP requests and asynchronously process the HTTP responses. You can get it a

On March 3, 2010, Ning social platform released a new Asynchronous HTTP Client library as open source. Its purpose is to allow Java applications to easily execute HTTP requests and asynchronously process the HTTP responses. You can get it at

http://github.com/ning/async-http-client

The Async HTTP Client library is simple to use. First, in order to add it to your Maven project, simply add this dependency:

<dependency>
    <groupId>com.ning</groupId>
    <artifactId>async-http-client</artifactId>
    <version>1.0.0-SNAPSHOT</version>
</dependency>

For now, you’ll have to add the Sonatype snapshot repo to your settings in order to be able to access the snapshot builds:

http://oss.sonatype.org/service/local/repositories/snapshots/content

Then in your code you can simply do:

    import com.ning.http.client.*;
    import java.util.concurrent.Future;

    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    Future<Response> f = asyncHttpClient.prepareGet("http://www.ning.com/").execute();
    Response r = f.get();

You can also accomplish asynchronous operation without using a Future if you want to receive and process the response in your handler:

    import com.ning.http.client.*;
    import java.util.concurrent.Future;

    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    asyncHttpClient.prepareGet("http://www.ning.com/").execute(new AsyncCompletionHandler(){

        @Override
        public Response onCompleted(Response response) throws Exception{
            // Do something with the Response
            // ...                                   `
            return response;
        }

        @Override
        public void onThrowable(Throwable t){
            // Something wrong happened.
        }
    });

You can also mix Future with AsyncHandler to only retrieve part of the asynchronous response

    import com.ning.http.client.*;
    import java.util.concurrent.Future;

    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    Future<Integer> f = asyncHttpClient.prepareGet("http://www.ning.com/")
          .execute(new AsyncCompletionHandler(){

        @Override
        public Integer onCompleted(Response response) throws Exception{
            // Do something with the Response
            return response.getStatusCode();
        }

        @Override
        public void onThrowable(Throwable t){
            // Something wrong happened.
        }
    });

    int statuѕCode = f.get();

You have full control on the Response life cycle, so you can decide at any moment to stop processing what the server is sending back:

      import com.ning.http.client.*;
      import java.util.concurrent.Future;

      AsyncHttpClient c = new AsyncHttpClient();
      Future<String> f = c.prepareGet("http://www.ning.com/").execute(new AsyncHandler() {
          private StringBuilder builder = new StringBuilder();

          @Override
          public STATE onStatusReceived(HttpResponseStatus status) throws Exception {
              int statusCode = status.getStatusCode();
              return STATE.CONTINUE;
          }

          @Override
          public STATE onHeadersReceived(HttpResponseHeaders h) throws Exception {
               Headers headers = h.getHeaders();
               // The headers have been read
               // If you don't want to read the body, or stop processing the response
               return STATE.ABORT;
          }

          @Override
          public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
               builder.append(new String(bodyPart.getBodyPartBytes()));
               return STATE.CONTINUE;
          }

          @Override
          public String onCompleted() throws Exception {
               // Will be invoked once the response has been fully read or a
               // ResponseComplete exception has been thrown.
               return builder.toString();
          }

          @Override
          public void onThrowable(Throwable t) {
          }
      });

      String bodyResponse = f.get();

Finally, you can also configure the AsyncHttpClient via it’s AsyncHttpClientConfig object:

        import com.ning.http.client.*;
        import java.util.concurrent.Future;

        AsyncHttpClientConfig cf = new AsyncHttpClientConfig.Builder()
                 .setProxyServer(new ProxyServer("127.0.0.1", 38080)).build();
        AsyncHttpClient c = new AsyncHttpClient(cf);

The library uses Java non blocking I/O for supporting asynchronous operations. The default asynchronous provider is build on top of Netty (http://www.jboss.org/netty), the Java NIO Client Server Socket Framework from JBoss, but the library exposes a configurable provider SPI which allows to easily plug in other frameworks.

Keep up to date on the library development by joining the Asynchronous HTTP Client discussion group.

(*) This blog has been written in collaboration with Thomas Dudziak

Author: Jeanfrancois Arcand

Jean-Francois Arcand works for Ning. He has previously worked 9 years for Sun Microsystems where he created Project Grizzly, Atmosphere and significantly contributed to the GlassFish Application Server. He is an active contributor on Project Atmosphere, Akka and sometimes contribute to project like Jersey, Tomcat and Jetty. He once and awhile blog on java.net and dzone.

21 thoughts on “Introducing Ning’s Asynchronous Http Client library.”

  1. This looks/sounds nice, but does it have a required dependency on commons logging like the other apache http client lib?

  2. Nice. Does the library comes with API to process dom element? Like find a particular element either by name or id and retrieve the value of the element?

  3. Hrm, looking like it requires Netty, which requires apache httpclient… which requires commons-logging 🙁

  4. Hi,

    First of all I would like to thank you for the all your contributions to open source society. My question will be related to Jersey Client. Does this can be utilized for Restful Resources?

    Thanks

  5. The library looks great. thanks for open sourcing it!

    As to the logging please have a look at SLF4J and Logback:

    http://www.slf4j.org/ (replacement for commons-logging)
    http://logback.qos.ch/ (replacement for log4j)

    Both are from the original log4j author.

    I would love to see the adoption of these rise. It’d be cool if new projects stopped using Log4j but it’s all to familiar to most developers 🙂

  6. which version of Netty does it require, I tried the latest stable release of Netty (3.1.5GA) and got the following exception:

    java.lang.NoSuchMethodError: org.jboss.netty.handler.codec.http.HttpRequest.setHeader(Ljava/lang/String;Ljava/lang/Object;)V
    at com.ning.http.client.providers.NettyAsyncHttpProvider.construct(NettyAsyncHttpProvider.java:350)
    at com.ning.http.client.providers.NettyAsyncHttpProvider.buildRequest(NettyAsyncHttpProvider.java:283)
    at com.ning.http.client.providers.NettyAsyncHttpProvider.access$700(NettyAsyncHttpProvider.java:108)
    at com.ning.http.client.providers.NettyAsyncHttpProvider$ConnectListener$Builder.build(NettyAsyncHttpProvider.java:242)
    at com.ning.http.client.providers.NettyAsyncHttpProvider.execute(NettyAsyncHttpProvider.java:506)
    at com.ning.http.client.AsyncHttpClient.executeRequest(AsyncHttpClient.java:385)
    at com.ning.http.client.AsyncHttpClient$BoundRequestBuilder.execute(AsyncHttpClient.java:197)

  7. Can anyone answer Sezgin Kucukkaraaslan’s question? I have the same problem:
    ava.lang.NoSuchMethodError: org.jboss.netty.handler.codec.http.HttpRequest.setHeader(Ljava/lang/String;Ljava/lang/Object;)V
    at com.ning.http.client.providers.NettyAsyncHttpProvider.construct(NettyAsyncHttpProvider.java:350)
    at com.ning.http.client.providers.NettyAsyncHttpProvider.buildRequest(NettyAsyncHttpProvider.java:283)
    at com.ning.http.client.providers.NettyAsyncHttpProvider.access$700(NettyAsyncHttpProvider.java:108)
    at com.ning.http.client.providers.NettyAsyncHttpProvider$ConnectListener$Builder.build(NettyAsyncHttpProvider.java:242)
    at com.ning.http.client.providers.NettyAsyncHttpProvider.execute(NettyAsyncHttpProvider.java:506)
    at com.ning.http.client.AsyncHttpClient.executeRequest(AsyncHttpClient.java:385)
    at com.ning.http.client.AsyncHttpClient$BoundRequestBuilder.execute(AsyncHttpClient.java:197)

  8. Hi!

    Is it a good idea to use this framework with Atmosphere? I tried it out and never get a response.
    What client is your recommendations to use with Atmoshpere?

    Regards,
    Pelle

  9. Definitely believe that which you stated. Your favorite reason seemed to be on the internet the easiest thing to be aware of. I say to you, I definitely get irked while people consider worries that they just don’t know about. You managed to hit the nail upon the top and also defined out the whole thing without having side-effects , people could take a signal. Will likely be back to get more. Thanks

  10. I think youve produced some really interesting points. Not too many people would truly think about this the way you just did. Im seriously impressed that theres so considerably about this topic thats been uncovered and you did it so properly, with so very much class. Very good one you, man! Definitely fantastic stuff right here.

Leave a Reply

Your email address will not be published. Required fields are marked *