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类库)
基础教程推荐
猜你喜欢
- IIS 6 的 PHP 最佳配置方法 2022-09-01
- Apache服务器配置攻略3 2022-09-01
- linux下安装apache与php;Apache+PHP+MySQL配置攻略 2023-08-07
- Apache Hudi数据布局黑科技降低一半查询时间 2022-10-06
- linux之conda环境安装全过程 2023-07-11
- centos 7 安装及配置zabbix agent 2023-09-24
- 服务器添加git钩子的步骤 2022-12-12
- nginx.conf(centos7 1.14)主配置文件修改 2023-09-23
- apache和nginx结合使用 2023-09-10
- 实战Nginx_取代Apache的高性能Web服务器 2023-09-29