Java Apache HttpClient5,同步、异步、fluent风格,代码案例

Apache HttpClient5

HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了 HttpClient。

pom.xml


    
        cn.hutool
        hutool-all
        5.5.9
    
    
        org.apache.httpcomponents.client5
        httpclient5
        5.1
    
    
        org.apache.httpcomponents.client5
        httpclient5-fluent
        5.0.3
    

代码案例

同步调用(经典)

import org.apache.commons.codec.Charsets;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.message.BasicNameValuePair;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HttpClientClassic {

    public static void main(String[] args) throws IOException {
        get();
        post();
    }

    public static void post() throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("https://www.toutiao.com/");
        List nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("username", "abcdef"));
        nvps.add(new BasicNameValuePair("password", "123456"));
        //这是一个form表单类型的数据格式,放入request body中
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, Charsets.UTF_8));
        //如果是json格式,如下处理,统一使用 UTF-8 可以避免 客户端与服务器端编码不一致问题
        //httpPost.setEntity(new StringEntity("{}",Charsets.UTF_8));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        System.out.println(response.getCode() + " " + response.getReasonPhrase());
        HttpEntity entity = response.getEntity();
        System.out.println(entity.getContent());
        EntityUtils.consume(entity);
    }

    public static void get() throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建一个get类型的http请求
        HttpGet httpGet = new HttpGet("https://www.toutiao.com/");
        CloseableHttpResponse response = httpClient.execute(httpGet);
        System.out.println(response.getCode() + " " + response.getReasonPhrase());
        HttpEntity entity = response.getEntity();
        System.out.println(entity.getContent());
        EntityUtils.consume(entity);
    }

}

异步调用

mport org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
import org.apache.hc.core5.concurrent.FutureCallback;
import org.apache.hc.core5.http.Method;

import java.util.concurrent.Future;

public class HttpClientAsync {

    public static void main(String[] args) throws Exception {
        //get1();
        get2();
    }

    public static void get1() throws Exception {
        CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
        httpclient.start();
        SimpleHttpRequest request = SimpleHttpRequest.create(Method.GET.name(), "http://www.baidu.com/");
        Future future = httpclient.execute(request, null);
        SimpleHttpResponse response = future.get();
        System.out.println(response.getBodyText());
    }

    public static void get2() throws Exception {
        CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
        httpclient.start();
        SimpleHttpRequest request = SimpleHttpRequest.create(Method.GET.name(), "http://www.baidu.com/");
        Future future = httpclient.execute(request, new FutureCallback() {


            @Override
            public void completed(SimpleHttpResponse response2) {
                System.out.println(request.getRequestUri() + "->" + response2.getCode());
            }

            @Override
            public void failed(Exception ex) {
                System.out.println(request.getRequestUri() + "->" + ex);
            }

            @Override
            public void cancelled() {
                System.out.println(request.getRequestUri() + " cancelled");
            }
        });
        SimpleHttpResponse response = future.get();
        System.out.println(response.getBodyText());
    }

}

fluent风格调用

import org.apache.hc.client5.http.async.methods.*;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
import org.apache.hc.core5.concurrent.FutureCallback;
import org.apache.hc.core5.http.Method;
import org.apache.hc.core5.http.message.StatusLine;
import org.apache.hc.core5.pool.PoolConcurrencyPolicy;
import org.apache.hc.core5.reactor.IOReactorConfig;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * fluent风格编程
 */
public class HttpClient5Demo {

    public static void main(String[] args) {
        // 异步应用配置
        IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
                .setSoTimeout(Timeout.ofMilliseconds(250))          // 超时时间
                .setSelectInterval(TimeValue.ofMilliseconds(50))    // 1.2
                .build();
        // setSoTimeout()====>连接上一个url,获取response的返回等待时间
        // setSelectInterval()====>NIO中设置select的间隔

        // 客户端连接配置
        PoolingAsyncClientConnectionManager build = PoolingAsyncClientConnectionManagerBuilder.create()
                .setPoolConcurrencyPolicy(PoolConcurrencyPolicy.LAX)  // 2.1
                .setMaxConnPerRoute(6).build();                       // 2.2
        // poolConcurrencyPolicy() ====> STRICT模式通过加锁的方式对,LAX通过cas的方式宽松计数
        // 设置STRICT,会使用StrictConnPool实现类;设置LAX ,会使用LaxConnPool实现类
        // maxConnPerRoute ====> 每个route最多能有多少个connection

        // 创建客户端
        CloseableHttpAsyncClient client = HttpAsyncClients.custom()
                .setIOReactorConfig(ioReactorConfig)
                .setConnectionManager(build)
                .disableAutomaticRetries()
                .build();
        // automaticRetriesDisabled===>关闭自动重试
        client.start();

        String uri = "http://www.baidu.com/";
        SimpleHttpRequest httpRequest = SimpleHttpRequest.create(Method.GET.name(), uri);
        final SimpleHttpRequest request = SimpleRequestBuilder.copy(httpRequest)
                .addParameter("name", "124")
                .build();

        RequestConfig config = RequestConfig.copy(RequestConfig.DEFAULT)
                .setConnectTimeout(150, TimeUnit.MILLISECONDS)
                .setConnectionRequestTimeout(200, TimeUnit.MILLISECONDS)
                .setResponseTimeout(100, TimeUnit.MILLISECONDS).build();
        request.setConfig(config);

        long start = System.currentTimeMillis();
        final Future future = client.execute(
                SimpleRequestProducer.create(request),
                SimpleResponseConsumer.create(),
                new FutureCallback() {

                    @Override
                    public void completed(final SimpleHttpResponse response) {
                        System.out.println(request + "->" + new StatusLine(response));
                        System.out.println(response.getBody());
                    }

                    @Override
                    public void failed(final Exception ex) {
                        System.out.println(request + "->" + ex);
                    }

                    @Override
                    public void cancelled() {
                        System.out.println(request + " cancelled");
                    }

                });

        // 时间计算
        try {
            SimpleHttpResponse simpleHttpResponse = future.get();
            System.out.println("body=" + simpleHttpResponse.getBodyText());
            long end = System.currentTimeMillis();
            System.out.println("时间差:" + (end - start));
        } catch (Exception e) {
            long end = System.currentTimeMillis();
            System.out.println("时间差:" + (end - start));
            System.out.println(e);
        }

        // 线程等待
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章