HttpClient介绍和使用

2021-03-28  本文已影响0人  晴天哥_王志

系列

简介

使用场景

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.14</version>
</dependency>
public class ClientExample {

    public static void main(String[] args) throws Exception {

        // 1、设置连接管理器
        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder
                .<ConnectionSocketFactory> create().register("http", plainsf).register("https", sslsf).build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
        cm.setMaxTotal(1000);
        cm.setDefaultMaxPerRoute(500);

        // 2、创建请求配置核心设置超时
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000)
                .setConnectTimeout(1000).setSocketTimeout(2000).build();

        // 3、创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.custom()
                .setConnectionManager(cm)
                .setDefaultRequestConfig(requestConfig)
                .build();

        // 4、发送请求并解析返回值
        HttpGet httpGet = new HttpGet("http://hc.apache.org/");
        CloseableHttpResponse response = httpclient.execute(httpGet);
        try {
            // 解析返回值
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, Charset.forName("utf8"));
            EntityUtils.consume(entity);
        } catch (Exception e) {

        } finally {
            // 关闭并释放连接,可能多余
            response.close();
        }
    }
}

请求过程解析

连接池

参考

上一篇 下一篇

猜你喜欢

热点阅读