Async POST in Java

September 14, 2010

I had a requirement to receive a CSV file via a HTTP post, and process it line by line after telling the user that we've received the file.

The best way I found to do this was to accept the file, perform an Async POST on a different local URL with the file, and then return the message back to the user. This second URL then splits the file into lines and processes line by line, waiting for one line to complete before passing in the next one.

The remainer of this post is about using the Async HTTP Client from http://github.com/ning/async-http-client to do a POST and not wait for the response.

This library has one dependency, jboss's netty which is available from http://www.jboss.org/netty

This code POSTs to lBaseUrl/offset with two parameters. It will not wait for a response - the response will be lost (in my case that's fine). See the example test code for the async-http-client for details of how to deal with the response.

import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Response;

import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

try
{
  AsyncHttpClient lAsyncHttpClient = new AsyncHttpClient();
  Future<Response> lFuture =
    lAsyncHttpClient.preparePost(lBaseUrl + "/offset")
                            .addParameter("Param1", lFirstParameter)
                            .addParameter("Param2", lSecondParameter)
                            .execute();
}
catch (IOException lException)
{
  throw new RuntimeException("IO Problems executing POST, underlying problem is " + lException.getMessage(), lException);
}
catch (ExecutionException lException)
{
  throw new RuntimeException("Execution problems executing POST, underlying problem is " + lException.getMessage(), lException);
}
catch (InterruptedException lException)
{
  throw new RuntimeException("Interrupted executing POST, underlying problem is " + lException.getMessage(), lException);
}

References

Tags: async http post java