views:

195

answers:

4

I'm fairly new to Java, so this may seem obvious to some. I've worked a lot with ActionScript, which is very much event based and I love that. I recently tried to write a small bit of Java code that does a POST request, but I've been faced with the problem that it's a synchronous request, so the code execution waits for the request to complete, time out or present an error.

How can I create an asynchronous request, where the code continues the execution and a callback is invoked when the HTTP request is complete? I've glanced at threads, but I'm thinking it's overkill.

+1  A: 

You may want to take a look at this question: http://stackoverflow.com/questions/592303/asynchronous-io-in-java

It looks like your best bet, if you don't want to wrangle the threads yourself is a framework. The previous post mentions Grizzly, https://grizzly.dev.java.net/, and Netty, http://www.jboss.org/netty/.

From the netty docs:

The Netty project is an effort to provide an asynchronous event-driven network application framework and tools for rapid development of maintainable high performance & high scalability protocol servers & clients.

Paul Rubel
+1  A: 

You may also want to look at Async Http Client.

kschneid
+1  A: 

I tried Apache Commons httpClient time ago for asynchronous http in Java. Take a look at this tutorial, examples are pretty straightforward.

http://hc.apache.org/httpclient-3.x/tutorial.html

Diego Pino
+1  A: 

Java is indeed more low level than ActionScript. It's like comparing apples with oranges. While ActionScript handles it all transparently "under the hood", in Java you need to manage the asynchronous processing (threading) yourself.

Fortunately, in Java there's the java.util.concurrent API which can do that in a nice manner.

Your problem can basically be solved as follows:

// Have one (or more) threads ready to do the async tasks. Do this during startup of your app.
ExecutorService executor = Executors.newFixedThreadPool(1); 

// Fire a request.
Future<Response> response = executor.submit(new Request(new URL("http://google.com")));

// Do your other tasks here (will be processed immediately, current thread won't block).
// ...

// Get the response (here the current thread will block until response is returned).
InputStream body = response.get().getBody();
// ...

// Shutdown the threads during shutdown of your app.
executor.shutdown();

wherein Request and Response look like follows:

public class Request implements Callable<Response> {
    private URL url;

    public Request(URL url) {
        this.url = url;
    }

    @Override
    public Response call() throws Exception {
        return new Response(url.openStream());
    }
}

and

public class Response {
    private InputStream body;

    public Response(InputStream body) {
        this.body = body;
    }

    public InputStream getBody() {
        return body;
    }
}

See also:

BalusC