Home > Ning > New Open Source Project Alert! A New Asynchronous Http Client library!

New Open Source Project Alert! A New Asynchronous Http Client library!

Introducing the new Asynchronous HTTP Client library, which allow applications to execute HTTP requests and asynchronously process the HTTP response .

IMG_0395.jpg

Read the official announcement here. Brian McCalister, Thomas Dudziak and I worked on that library since I’ve joinned NIng back in December.

The library 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/AsyncHttpClient/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();
               // The Status have been read
               // If you don't want to read the headers,body, or stop processing the response
               return STATE.CONTINUE; // Or STATE.ABORT
          }

          @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 or ask your questions directly by following me on twitter.

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

technorati:

About these ads
Categories: Ning
  1. Jérôme
    August 11, 2010 at 2:46 pm

    Hi,

    Quick question on the choice of Netty. Why ain’t you using Grizzly ?

    Regards,

    Jérôme

    • August 27, 2010 at 8:30 pm

      Salut,

      Grizzly 1.9.x doesn’t have a client side library, unfortuanly. Grizzly 2.0 is having one and it should be simple to replace the Netty provider with it.

      A+

      – Jeanfrancois

  1. June 23, 2010 at 5:19 pm
  2. July 20, 2010 at 5:50 am
  3. September 5, 2010 at 9:12 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 50 other followers

%d bloggers like this: