使用HttpAsyncClient进行异步获取数据
2018-07-20 来源:open-open
package com.k.ctc.code.asynchttp; 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; /** * @author Kai * @Date 2016-1-6 11:14:56 * @Desc */ public class AsyncClient { public static void main(String[] args) throws Exception { // 设置HTTP请求的超时配置 RequestConfig config = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build(); // 根据配置创建异步的HTTP客户端 CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(config).build(); //运行客户端 httpclient.start(); //构建5个HTTPGET请求 HttpGet[] requests = new HttpGet[]{ new HttpGet("https://www.baidu.com/"), new HttpGet("https://www.baidu.com/"), new HttpGet("https://www.baidu.com/"), new HttpGet("https://www.baidu.com/"), new HttpGet("https://www.baidu.com/")}; //创建一个计数器 final CountDownLatch latch = new CountDownLatch(requests.length); //循环请求 for (final HttpGet get : requests) { httpclient.execute(get, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse t) { latch.countDown(); System.out.println("=================================="); System.out.println(t.getStatusLine()); } @Override public void failed(Exception excptn) { latch.countDown(); System.out.println("HttpGet failed"); } @Override public void cancelled() { latch.countDown(); System.out.println("HttpGet cancelled"); } }); } //等待5个都请求完成 latch.await(); System.out.println("Shutting down"); //关闭 httpclient.close(); } }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐