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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM