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

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.

解决方案

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 = 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 {

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:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值