Ning’s Async Http Client and Twitter Streaming API

Recently I played with the Apache Wink REST Client to access the Twitter Streaming API. Yesterday Jean-Francois Arcand announced the availability of Ning’s new Async Http Client. The blog looked interesting and the Twitter stream is a perfect example to combine the two. If you are behind a firewall you need to set a proxy-server on the AsyncHttpClientConfig and pass it into the constructor of the AsyncHttpClient. After that, you simply call the prepareGet(…) and here you pass in an anonymous AsyncCompletionHandler:

String logon = "user:password";
String encodedLogon = new BASE64Encoder().encode(logon.getBytes());

AsyncHttpClientConfig cc = new AsyncHttpClientConfig.Builder()
 new ProxyServer(Protocol.HTTP, "my-proxy", 8080)

AsyncHttpClient asyncHttpClient = new AsyncHttpClient(cc);

 Future<Response> f = asyncHttpClient.prepareGet(
 .addHeader("Authorization","Basic " + encodedLogon)
 .execute(new AsyncCompletionHandler()
 public STATE onBodyPartReceived(HttpResponseBodyPart content)
 throws Exception
 System.out.println("Tweet: " + new String(content.getBodyPartBytes()));

 public Object onCompleted(Response response) throws Exception
 // TODO Auto-generated method stub
 return response;
 public void onThrowable(Throwable arg0)

 Response r = f.get();

The interesting part of the anonymous implementation is its onBodyPartReceived(). Once the Twitter server has put a new tweet into the stream, the callback is called as soon as the actual (JSON) output arrives your client machine. In here, you could parse the JSON can trigger different methods of your application, based on what you want.

The AsyncHttpClient is pretty interesting – However I noticed a limitation that no parameters are allowed on GET request. Not via its setParameter/s() method nor via using the ? character => http://server_url?param=value.

Need to check more by checking out the code from here.

Parameters with HTTP POST

Of course, doing a HTTP_POST the parameters work as expected 😉

Request req = new
 .addHeader("Authorization","Basic" + encodedLogon)
 .setParameter("track", "Java")

 Future<Response> f = asyncHttpClient.executeRequest(req,
  new AsyncCompletionHandler()
 // similar as above...

Looking forward to continue using this neat project! Good job guys…


Posted in ajax, apache, comet, fun, jetty, web²
One comment on “Ning’s Async Http Client and Twitter Streaming API
  1. matthiaswessendorf says:

    Open Source is really fast.

    My patch has already been committed to the GITHUB:

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: