import java.util.concurrent.CountDownLatch;import org.apache.http.HttpResponse;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.methods.HttpGet;import org.apache.http.c...
import java.util.concurrent.CountDownLatch; import org.apache.http.HttpResponse; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.concurrent.FutureCallback; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; public class AsyncClientHttpExchangeFutureCallback { public static void main(final String[] args) throws Exception { RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(3000) .setConnectTimeout(3000).build(); CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom() .setDefaultRequestConfig(requestConfig) .build(); try { httpclient.start(); final HttpGet[] requests = new HttpGet[] { new HttpGet("http://www.apache.org/"), new HttpGet("https://www.verisign.com/"), new HttpGet("http://www.googleXXXXXXXXXXXXXXXXXXXXXX.com/") }; final CountDownLatch latch = new CountDownLatch(requests.length); for (final HttpGet request: requests) { httpclient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(final HttpResponse response) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + response.getStatusLine()); } @Override public void failed(final Exception ex) { latch.countDown(); System.out.println(request.getRequestLine() + "->" + ex); } @Override public void cancelled() { latch.countDown(); System.out.println(request.getRequestLine() + " cancelled"); } }); } latch.await(); System.out.println("Shutting down"); } finally { httpclient.close(); } System.out.println("Done"); } }
原文:http://www.cnblogs.com/starcrm/p/5216303.html
沃梦达教程
本文标题为:Java异步执行多个HTTP请求的例子(需要apache http类库)
猜你喜欢
- CentOS7安装GlusterFS集群的全过程 2022-10-10
- IIS搭建ftp服务器的详细教程 2022-11-15
- 阿里云ECS排查CPU数据分析 2022-10-06
- 教你在docker 中搭建 PHP8 + Apache 环境的过程 2022-10-06
- nginx中封禁ip和允许内网ip访问的实现示例 2022-09-23
- 解决:apache24 安装后闪退和配置端口映射和连接超时设置 2023-09-11
- 利用Docker 运行 python 简单程序 2022-10-16
- CentOS_mini下安装docker 之 安装docker CE 2023-09-23
- KVM虚拟化Linux Bridge环境部署的方法步骤 2023-07-11
- 【转载】CentOS安装Tomcat 2023-09-24