使用HttpAsyncClient进行异步获取数据

为什么80%的码农都做不了架构师?>>>   hot3.png

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

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


以下是使用Maven引用的jar(并不知道是不是都有使用到):

 
     4.4
 

 
 
    org.apache.httpcomponents
    httpasyncclient
    4.1


    org.apache.httpcomponents
    httpclient
    ${httpclient.version}


    org.apache.httpcomponents
    httpcore
    ${httpclient.version}


    org.apache.httpcomponents
    httpcore-nio
    ${httpclient.version}



转载于:https://my.oschina.net/Kxvz/blog/598260

你可能感兴趣的:(使用HttpAsyncClient进行异步获取数据)