http异步请求 java_如何在JAVA中创建异步HTTP请求?

Java确实比ActionScript更低级。这就像比较苹果和橘子。虽然ActionScript处理所有透明的“底层”,在Java中,你需要自己管理异步处理(线程)。

幸运的是,在Java中有java.util.concurrent API可以以一种很好的方式做到这一点。

你的问题基本上可以解决如下:

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

其中请求和响应如下:

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

}

}

public class Response {

private InputStream body;

public Response(InputStream body) {

this.body = body;

}

public InputStream getBody() {

return body;

}

}

也可以看看:

> Lesson: Concurrency – 一个java.util.concurrent教程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值