你如何在Java中创建一个异步HTTP请求?

你如何在Java中创建一个异步HTTP请求?

问题描述:

我是相当新的Java,所以这看起来明显一些。我已经做了很多使用ActionScript,这是基于非常事件,我很喜欢。我最近尝试编写Java code,做一个POST请求的小一点,但我一直在面对,这是一个同步的请求的问题,所以code执行等待请求完成,时间出或present错误。

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.

我怎样才能创建一个异步请求,其中code继续执行和回调HTTP请求完成时被调用?我在线程一眼,但我想这是矫枉过正。

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.

Java的确实比较低的水平比动作。这就像橘子比较苹果。虽然动作处理这一切透明引擎盖下,在Java中,你需要管理的异步处理(线程)自己。

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.

幸运的是,在Java中还有的java.util.concurrent$c$c> API,它可以做到在一个不错的方式。

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();

,其中请求响应看起来如下:

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());
    }
}

public class Response {
    private InputStream body;

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

    public InputStream getBody() {
        return body;
    }
}

参见:


  • 课:并发 - 一个的java.util.concurrent 教程。

  • See also:

    • Lesson: Concurrency - a java.util.concurrent tutorial.