HttpClient学习(三)—— AsyncHttpClient使用

一、介绍

This class support asynchronous and synchronous HTTP requests.

AsyncHttpClient 支持同步、异步Http请求。

二、简单使用

引入依赖


<dependencies>

        <dependency>
            <groupId>org.asynchttpclient</groupId>
            <artifactId>async-http-client</artifactId>
            <version>2.8.1</version>
        </dependency>

        <dependency>
            <groupId>net.tascalate</groupId>
            <artifactId>net.tascalate.concurrent</artifactId>
            <version>0.8.0</version>
        </dependency>

    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>


执行同步请求


/**
     * 执行同步HTTP请求
     */
    public void synRequest() {

        String url = "http://www.baidu.com";
        AsyncHttpClient c = new DefaultAsyncHttpClient();
        Future<Response> f = c.prepareGet(url).execute();
        try {
            System.out.println(f.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }


执行异步请求


/**
     * 执行异步HTTP请求
     */
    public void asyncRequest() {

        String url = "http://www.baidu.com";
        AsyncHttpClient c = new DefaultAsyncHttpClient();
        Future<Response> f = c.prepareGet(url).execute(new AsyncCompletionHandler<Response>() {

            // onCompleted method will be invoked once the http response has been fully read.
            //一旦完全读取Http响应,就调用onCompleted方法
            //Response object includes the http headers and the response body.
            //Response 对象包括HTTP请求头和响应体
            @Override
            public Response onCompleted(Response response) throws Exception {
                System.out.println("完成请求");
                return response;
            }

            @Override
            public void onThrowable(Throwable t) {
                System.out.println("出现异常");
                super.onThrowable(t);
            }
        });

        try {
            Response response = f.get();
            System.out.println(response.getResponseBody());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }


配置



private AsyncHttpClient client = asyncHttpClient(
            new DefaultAsyncHttpClientConfig.Builder()
                    .setFollowRedirect(true)
                    .setProxyServerSelector(new ProxySelector())
                    .setIoThreadsCount(Runtime.getRuntime().availableProcessors() * 2)
                    .setConnectTimeout(1000)
                    .setReadTimeout(1000)
                    .setRequestTimeout(3000)
                    .setMaxRequestRetry(2)
                    .setThreadPoolName("ASYNC-CLIENT")
    );



private class ProxySelector implements ProxyServerSelector {

        @Override
        public ProxyServer select(Uri uri) {
           //从代理池中获取HttpHost
            final HttpHost proxy = getProxy(uri.getHost());
            if (proxy == null) {
                return null;
            }
            final ProxyServer.Builder builder = new ProxyServer.Builder(proxy.getHostName(), proxy.getPort());
            return builder.build();
        }
    }



参考文档

《AsyncHttpClient 官方文档》

posted @ 2019-05-21 20:28  清泉白石  阅读(10414)  评论(0编辑  收藏  举报