• 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 官方文档》

  • 相关阅读:
    [opentwebst]一个简单的登陆脚本
    opentwebst一个ie自动化操作测试软件-功能强大
    给X9DRL-iF双路服务器主板刷BIOS
    在ubuntu16下面通过kvm+lvm安装ubuntu16的虚拟机
    ubuntu16安装KVM
    PowerShell全自动分配CPU
    在ubuntu16编译安装nginx-1.10.2(full)完全自带组件
    将博客搬至CSDN
    乌邦图ubuntu配置iptables的NAT上网
    LVM增大和减小ext4、xfs分区
  • 原文地址:https://www.cnblogs.com/fonxian/p/10902172.html
Copyright © 2020-2023  润新知