Java 中使用 HttpClient 工具详解

Java 中使用 HttpClient 工具详解

文章目录

  !版权声明:本博客内容均为原创,每篇博文作为知识积累,写博不易,转载请注明出处。


系统环境:

  • JDK 版本:1.8
  • HttpClient 版本:5.0

参考地址:

一、HttpClient 简介

       超文本传输协议(HTTP)可能是当今 Internet 上使用的最重要的协议。Web 服务,支持网络的设备和网络计算的增长继续将 HTTP 协议的作用扩展到用户驱动的Web浏览器之外,同时增加了需要 HTTP 支持的应用程序的数量。

       尽管 java.net 软件包提供了用于通过 HTTP 访问资源的基本功能,但它并未提供许多应用程序所需的全部灵活性或功能。HttpClient 试图通过提供高效,最新且功能丰富的程序包来实现此空白,以实现最新 HTTP 标准和建议的客户端。

       HttpClient 是为扩展而设计的,同时提供了对基本 HTTP 协议的强大支持,对于构建 HTTP 感知的客户端应用程序(例如 Web 浏览器,Web 服务客户端或利用或扩展 HTTP 协议进行分布式通信的系统)的任何人来说,HttpClient 都可能会感兴趣。

二、示例前准备

1、接口测试 Server 项目

       在介绍如何使用 HttpClient 的示例前,需要提前准备示例项目进行测试的接口,这里本人使用 SpringBoot 提前写了个测试项目,用于后续方便演示,该测试项目 Github 地址为:https://github.com/my-dlq/blog-example/tree/master/java/java-httpclient-example

2、HttpClient 工具使用 Client 项目

(1)、Maven 引入相关依赖

这里是使用 Maven 管理示例项目中的依赖,下面除了需要引入 httpclient 依赖外,还需要引入 logbacklombokfastjson 相关依赖来提供使用工具时的便利,其中每个依赖的作用分别为:

  • logback:日志框架,方便打印日志。
  • fastjson:用于转换 Json 的工具框架。
  • lombok:这里是用于方便快速实现实体类的 Get 与 Set 方法,且集成 Slf4j 方法与各个日志框架融合。
 1<?xml version="1.0" encoding="UTF-8"?>
 2<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 4    <modelVersion>4.0.0</modelVersion>
 5
 6    <groupId>club.mydlq</groupId>
 7    <artifactId>java-httpclient-use-example</artifactId>
 8    <version>1.0.0</version>
 9    <name>java-httpclient-use-example</name>
10    <description>java httpclient use example</description>
11
12    <properties>
13        <java.version>1.8</java.version>
14    </properties>
15
16    <dependencies>
17        <!--httpclient-->
18        <dependency>
19            <groupId>org.apache.httpcomponents.client5</groupId>
20            <artifactId>httpclient5</artifactId>
21            <version>5.0</version>
22        </dependency>
23        <!--fastjson-->
24        <dependency>
25            <groupId>com.alibaba</groupId>
26            <artifactId>fastjson</artifactId>
27            <version>1.2.62</version>
28        </dependency>
29        <!-- lombok -->
30        <dependency>
31            <groupId>org.projectlombok</groupId>
32            <artifactId>lombok</artifactId>
33            <version>1.18.12</version>
34            <optional>true</optional>
35        </dependency>
36        <!--logback-->
37        <dependency>
38            <groupId>ch.qos.logback</groupId>
39            <artifactId>logback-core</artifactId>
40            <version>1.2.3</version>
41        </dependency>
42        <dependency>
43            <groupId>ch.qos.logback</groupId>
44            <artifactId>logback-classic</artifactId>
45            <version>1.2.3</version>
46        </dependency>
47    </dependencies>
48
49</project>

(2)、用于测试的实体类 UserInfo

为了方便后续测试 Json 序列化传递消息的示例,这里提前封装一个用于测试的实体类。

 1import lombok.Data;
 2import lombok.ToString;
 3
 4@Data
 5@ToString
 6public class UserInfo {
 7
 8    private String name;
 9    private String sex;
10
11}

二、HttpClient 使用示例(同步)

1、HttpClient 工具类封装

  1import lombok.extern.slf4j.Slf4j;
  2import org.apache.hc.client5.http.config.RequestConfig;
  3import org.apache.hc.client5.http.cookie.BasicCookieStore;
  4import org.apache.hc.client5.http.cookie.CookieStore;
  5import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
  6import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
  7import org.apache.hc.client5.http.impl.classic.HttpClients;
  8import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
  9import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
 10import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory;
 11import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
 12import org.apache.hc.core5.http.config.Registry;
 13import org.apache.hc.core5.http.config.RegistryBuilder;
 14import org.apache.hc.core5.http.io.SocketConfig;
 15import org.apache.hc.core5.util.TimeValue;
 16import java.io.IOException;
 17import java.util.concurrent.TimeUnit;
 18
 19@Slf4j
 20public class HttpClientUtil {
 21
 22    private HttpClientUtil(){}
 23
 24    /** HttpClient 对象 */
 25    private static CloseableHttpClient httpClient = null;
 26    /** CookieStore 对象 */
 27    private static CookieStore cookieStore = null;
 28    /** Basic Auth 管理对象 **/
 29    private static BasicCredentialsProvider basicCredentialsProvider = null;
 30
 31    // Httpclient 初始化
 32    static {
 33        // 注册访问协议相关的 Socket 工厂
 34        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
 35                .register("http", PlainConnectionSocketFactory.getSocketFactory())
 36                .register("https", SSLConnectionSocketFactory.getSocketFactory())
 37                .build();
 38        // Http 连接池
 39        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);
 40        poolingHttpClientConnectionManager.setDefaultSocketConfig(SocketConfig.custom()
 41                .setSoTimeout(30,TimeUnit.SECONDS)
 42                .setTcpNoDelay(true).build()
 43        );
 44        poolingHttpClientConnectionManager.setMaxTotal(200);
 45        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(200);
 46        poolingHttpClientConnectionManager.setValidateAfterInactivity(TimeValue.ofMinutes(5));
 47        // Http 请求配置
 48        RequestConfig requestConfig = RequestConfig.custom()
 49                .setConnectTimeout(5000, TimeUnit.MILLISECONDS)
 50                .setResponseTimeout(5000, TimeUnit.MILLISECONDS)
 51                .setConnectionRequestTimeout(5000, TimeUnit.MILLISECONDS)
 52                .build();
 53        // 设置 Cookie
 54        cookieStore = new BasicCookieStore();
 55        // 设置 Basic Auth 对象
 56        basicCredentialsProvider = new BasicCredentialsProvider();
 57        // 创建监听器,在 JVM 停止或重启时,关闭连接池释放掉连接
 58        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
 59            try {
 60                log.info("执行关闭 HttpClient");
 61                httpClient.close();
 62                log.info("已经关闭 HttpClient");
 63            } catch (IOException e) {
 64                log.error(e.getMessage(), e);
 65            }
 66        }));
 67        // 创建 HttpClient 对象
 68        httpClient = HttpClients.custom()
 69                // 设置 Cookie
 70                .setDefaultCookieStore(cookieStore)
 71                // 设置 Basic Auth
 72                .setDefaultCredentialsProvider(basicCredentialsProvider)
 73                // 设置 HttpClient 请求参数
 74                .setDefaultRequestConfig(requestConfig)
 75                // 设置连接池
 76                .setConnectionManager(poolingHttpClientConnectionManager)
 77                // 设置定时清理连接池中过期的连接
 78                .evictExpiredConnections()
 79                .evictIdleConnections(TimeValue.ofMinutes(3))
 80                .build();
 81    }
 82
 83    /**
 84     * 获取 Httpclient 对象
 85     *
 86     * @return CloseableHttpClient
 87     */
 88    public static CloseableHttpClient getHttpclient() {
 89        return httpClient;
 90    }
 91
 92    /**
 93     * 获取 CookieStore 对象
 94     *
 95     * @return CookieStore
 96     */
 97    public static CookieStore getCookieStore() {
 98        return cookieStore;
 99    }
100
101    /**
102     * 获取 BasicCredentialsProvider 对象
103     *
104     * @return BasicCredentialsProvider
105     */
106    public static BasicCredentialsProvider getBasicCredentialsProvider(){
107        return basicCredentialsProvider;
108    }
109
110}

2、基本操作示例

HttpClient 基本 get、post、form 表单等操作示例:

  1import club.mydlq.entity.UserInfo;
  2import club.mydlq.utils.HttpClientUtil;
  3import com.alibaba.fastjson.JSON;
  4import lombok.extern.slf4j.Slf4j;
  5import org.apache.hc.client5.http.classic.methods.HttpGet;
  6import org.apache.hc.client5.http.classic.methods.HttpPost;
  7import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
  8import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
  9import org.apache.hc.core5.http.*;
 10import org.apache.hc.core5.http.io.entity.EntityUtils;
 11import org.apache.hc.core5.http.io.entity.StringEntity;
 12import org.apache.hc.core5.http.message.BasicNameValuePair;
 13import java.io.IOException;
 14import java.io.InputStream;
 15import java.nio.charset.StandardCharsets;
 16import java.util.ArrayList;
 17import java.util.List;
 18
 19/**
 20 * HttpClient 基本 get、post、form 表单等操作示例
 21 */
 22@Slf4j
 23public class BaseExample {
 24
 25    /**
 26     * Http Get 请求示例
 27     */
 28    public static void httpGet() {
 29        CloseableHttpResponse response = null;
 30        try {
 31            // 创建 HttpGet 对象
 32            HttpGet httpGet = new HttpGet("http://localhost:8080/base/get?name=mydlq&sex=man");
 33            // 执行 Http Get 请求
 34            response = HttpClientUtil.getHttpclient().execute(httpGet);
 35            // 输出响应内容
 36            if (response.getEntity() != null) {
 37                log.info(EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));
 38            }
 39            // 销毁流
 40            EntityUtils.consume(response.getEntity());
 41        } catch (IOException | ParseException e) {
 42            log.error("", e);
 43        } finally {
 44            // 释放资源
 45            if (response != null) {
 46                try {
 47                    response.close();
 48                } catch (IOException e) {
 49                    log.error("", e);
 50                }
 51            }
 52        }
 53    }
 54
 55    /**
 56     * Http Post Form 表单请求示例
 57     */
 58    public static void httpPostForm(){
 59        CloseableHttpResponse response = null;
 60        try {
 61            // 创建 HttpPost 对象
 62            HttpPost httpPost = new HttpPost("http://localhost:8080/base/form");
 63            // 设置 HttpPost 请求参数
 64            List<NameValuePair> params = new ArrayList<>(2);
 65            params.add(new BasicNameValuePair("name", "mydlq"));
 66            params.add(new BasicNameValuePair("sex", "man"));
 67            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
 68            httpPost.setEntity(urlEncodedFormEntity);
 69            // 设置 Content-Type
 70            httpPost.addHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
 71            // 执行 Http Post 请求
 72            response = HttpClientUtil.getHttpclient().execute(httpPost);
 73            // 输出响应内容
 74            if (response.getEntity() != null) {
 75                log.info(EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));
 76            }
 77            // 销毁流
 78            EntityUtils.consume(urlEncodedFormEntity);
 79            EntityUtils.consume(response.getEntity());
 80        } catch (IOException | ParseException e) {
 81            log.error("",e);
 82        } finally {
 83            // 释放资源
 84            if (response != null) {
 85                try {
 86                    response.close();
 87                } catch (IOException e) {
 88                    log.error("", e);
 89                }
 90            }
 91        }
 92    }
 93
 94    /**
 95     * Http Post Json 表单请求示例
 96     */
 97    public static void httpPostJson(){
 98        CloseableHttpResponse response = null;
 99        InputStream inputStream = null;
100        try {
101            // 创建 HttpPost 对象
102            HttpPost httpPost = new HttpPost("http://localhost:8080/base/json");
103            // 设置请求对象
104            UserInfo requestUserInfo = new UserInfo();
105            requestUserInfo.setName("mydlq");
106            requestUserInfo.setSex("man");
107            // 将请求对象通过 fastjson 中方法转换为 Json 字符串,并创建字符串实体对象
108            StringEntity stringEntity = new StringEntity(JSON.toJSONString(requestUserInfo), StandardCharsets.UTF_8);
109            // 设置 HttpPost 请求参数
110            httpPost.setEntity(stringEntity);
111            // 设置 Content-Type
112            httpPost.addHeader("Content-Type",ContentType.APPLICATION_JSON);
113            // 执行 Http Post 请求
114            response = HttpClientUtil.getHttpclient().execute(httpPost);
115            // 输出响应内容
116            if (response.getEntity() != null) {
117                inputStream = response.getEntity().getContent();
118                UserInfo userInfo = JSON.parseObject(inputStream, UserInfo.class);
119                log.info(userInfo.toString());
120            }
121            // 销毁流
122            EntityUtils.consume(stringEntity);
123            EntityUtils.consume(response.getEntity());
124        } catch (IOException e) {
125            log.error("",e);
126        } finally {
127            // 释放资源
128            if (inputStream != null){
129                try {
130                    inputStream.close();
131                } catch (IOException e) {
132                    log.error("", e);
133                }
134            }
135            if (response != null) {
136                try {
137                    response.close();
138                } catch (IOException e) {
139                    log.error("", e);
140                }
141            }
142        }
143    }
144
145    /** 测试 Main 方法 */
146    public static void main(String[] args) {
147        // 执行 Http Get 请求
148        httpGet();
149        // 执行 Http Post Form 表单请求
150        httpPostForm();
151        // 执行 Http Post Json 请求
152        httpPostJson();
153    }
154
155}

3、Form 表单登录示例

 1import club.mydlq.utils.HttpClientUtil;
 2import lombok.extern.slf4j.Slf4j;
 3import org.apache.hc.client5.http.classic.methods.HttpGet;
 4import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
 5import org.apache.hc.core5.http.ClassicHttpRequest;
 6import org.apache.hc.core5.http.ParseException;
 7import org.apache.hc.core5.http.io.entity.EntityUtils;
 8import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
 9import java.io.IOException;
10import java.nio.charset.StandardCharsets;
11
12@Slf4j
13public class LoginExample {
14
15    /**
16     * Form 表单登录,登录成功后会自动存 Session,然后再访问一个需要鉴权的页面
17     */
18    public static void httpFormLogin() {
19        CloseableHttpResponse response = null;
20        try {
21            // 创建 Http 请求
22            ClassicHttpRequest request = ClassicRequestBuilder.post("http://localhost:8080/login/from")
23            		// 设置编码,防止中文乱码
24            		.setCharset(StandardCharsets.UTF_8)  
25                    .addParameter("t_username", "admin")
26                    .addParameter("t_password", "123456")
27                    .build();
28            // 执行 Http 请求,进行登录
29            HttpClientUtil.getHttpclient().execute(request);
30            // 如果登录成功,则能获取 sessionid
31            String jsessionid = HttpClientUtil.getCookieStore().getCookies().get(0).getValue();
32            log.info("获取的 sessionid 为:{}", jsessionid);
33            // 创建 HttpGet 对象
34            HttpGet httpGet = new HttpGet("http://localhost:8080/login/test");
35            // 执行 Http Get 请求进行测试
36            response = HttpClientUtil.getHttpclient().execute(httpGet);
37            // 输出响应内容
38            if (response.getEntity() != null) {
39                log.info(EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));
40            }
41            // 销毁流
42            EntityUtils.consume(response.getEntity());
43        } catch (IOException | ParseException e) {
44            log.error("", e);
45        } finally {
46            if (response != null) {
47                try {
48                    response.close();
49                } catch (IOException e) {
50                    log.error("", e);
51                }
52            }
53        }
54    }
55
56    /** 测试 Main 方法 */
57    public static void main(String[] args) {
58        // 执行 Form 表单登录
59        httpFormLogin();
60    }
61
62}

4、Basic Auth 验证示例

 1import club.mydlq.utils.HttpClientUtil;
 2import lombok.extern.slf4j.Slf4j;
 3import org.apache.hc.client5.http.auth.AuthScope;
 4import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
 5import org.apache.hc.client5.http.classic.methods.HttpGet;
 6import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
 7import org.apache.hc.core5.http.ParseException;
 8import org.apache.hc.core5.http.io.entity.EntityUtils;
 9import java.io.IOException;
10import java.nio.charset.StandardCharsets;
11
12@Slf4j
13public class BasicAuthExample {
14
15    /**
16     * Basic Auth 访问验证测试
17     */
18    public static void httpBasicAuth() {
19        CloseableHttpResponse response = null;
20        // 配置 Credentials
21        HttpClientUtil.getBasicCredentialsProvider().setCredentials(
22                new AuthScope("localhost", 8080),
23                new UsernamePasswordCredentials("admin", "123456".toCharArray()));
24        try {
25            // 创建 Http 请求
26            HttpGet httpget = new HttpGet("http://localhost:8080/basic/test");
27            // 执行 Http 请求,进行登录
28            response = HttpClientUtil.getHttpclient().execute(httpget);
29            // 输出响应内容
30            if (response.getEntity() != null) {
31                log.info(EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));
32            }
33            // 销毁流
34            EntityUtils.consume(response.getEntity());
35        } catch (IOException | ParseException e) {
36            log.error("", e);
37        } finally {
38            if (response != null) {
39                try {
40                    response.close();
41                } catch (IOException e) {
42                    log.error("", e);
43                }
44            }
45        }
46    }
47
48    /** 测试 Main 方法 */
49    public static void main(String[] args) {
50        // 访问需要 BasicAuth 验证的地址,进行测试
51        httpBasicAuth();
52    }
53
54}

5、文件上传、下载示例

  1import club.mydlq.utils.HttpClientUtil;
  2import lombok.extern.slf4j.Slf4j;
  3import org.apache.hc.client5.http.classic.methods.HttpGet;
  4import org.apache.hc.client5.http.classic.methods.HttpPost;
  5import org.apache.hc.client5.http.entity.mime.*;
  6import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
  7import org.apache.hc.core5.http.*;
  8import org.apache.hc.core5.http.io.entity.EntityUtils;
  9import java.io.*;
 10import java.net.URLDecoder;
 11import java.nio.charset.StandardCharsets;
 12
 13@Slf4j
 14public class FileExample {
 15
 16    /**
 17     * Http Post 上传文件示例
 18     */
 19    public static void httpPostUpload() {
 20        File file = new File("D:" +File.separator + "测试.xlsx");
 21        CloseableHttpResponse response = null;
 22        try {
 23            HttpPost httpPost = new HttpPost("http://localhost:8080/file/upload");
 24            HttpEntity entity = MultipartEntityBuilder.create()
 25                    // 设置编码方式
 26                    .setCharset(StandardCharsets.UTF_8)
 27                    // 设置为兼容模式,解决返回中文乱码问题
 28                    .setMode(HttpMultipartMode.LEGACY)
 29                    .addPart("file", new FileBody(file))
 30                    .build();
 31            httpPost.setEntity(entity);
 32            // 执行提交
 33            response = HttpClientUtil.getHttpclient().execute(httpPost);
 34            // 输出响应内容
 35            if (response.getEntity() != null) {
 36                log.info(EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));
 37            }
 38            // 销毁流
 39            EntityUtils.consume(response.getEntity());
 40        } catch (IOException | ParseException e) {
 41            log.error("", e);
 42        } finally {
 43            // 释放资源
 44            if (response != null) {
 45                try {
 46                    response.close();
 47                } catch (IOException e) {
 48                    log.error("", e);
 49                }
 50            }
 51        }
 52    }
 53
 54    /**
 55     * Http Get 下载文件示例
 56     */
 57    public static void httpGetDownload() {
 58        CloseableHttpResponse response = null;
 59        try {
 60            // 创建 HttpGet 对象
 61            HttpGet httpGet = new HttpGet("http://localhost:8080/file/download");
 62            // 执行 Http Get 请求
 63            response = HttpClientUtil.getHttpclient().execute(httpGet);
 64            // 从 headers 中获取文件名
 65            String content = response.getHeader("Content-Disposition").getValue();
 66            String filename = content.substring(content.lastIndexOf('=') + 1, content.lastIndexOf('.'));
 67            String suffix = content.substring(content.lastIndexOf('.'));
 68            // 将文件名转码
 69            filename = URLDecoder.decode(filename, "UTF-8");
 70            // 获取响应实体对象
 71            HttpEntity entity = response.getEntity();
 72            if (entity != null){
 73                // 获取输入流并且将保存下载的文件
 74                try (InputStream inputStream = entity.getContent();
 75                     FileOutputStream fileOutputStream = new FileOutputStream("d://" + filename + suffix)
 76                ) {
 77                    byte[] tmp = new byte[1024];
 78                    int l;
 79                    while ((l = inputStream.read(tmp)) != -1) {
 80                        fileOutputStream.write(tmp, 0, l);
 81                    }
 82                    fileOutputStream.flush();
 83                }
 84            }
 85            // 销毁流
 86            EntityUtils.consume(response.getEntity());
 87        } catch (IOException | ProtocolException e) {
 88            log.error("", e);
 89        } finally {
 90            // 释放资源
 91            if (response != null) {
 92                try {
 93                    response.close();
 94                } catch (IOException e) {
 95                    log.error("", e);
 96                }
 97            }
 98        }
 99    }
100
101    /** 测试 Main 方法 */
102    public static void main(String[] args) {
103        // 执行下载文件
104        httpGetDownload();
105        // 执行上传文件
106        httpPostUpload();
107    }
108
109}

三、HttpClient 使用示例(异步)

1、HttpAsyncClient 工具类封装

 1import lombok.extern.slf4j.Slf4j;
 2import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
 3import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
 4import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
 5import org.apache.hc.core5.reactor.IOReactorConfig;
 6import org.apache.hc.core5.util.TimeValue;
 7
 8@Slf4j
 9public class HttpClientAsycnUtil {
10
11    /**
12     * HttpAsyncClient 对象
13     */
14    private static CloseableHttpAsyncClient closeableHttpAsyncClient = null;
15
16    // HttpAsyncclient 初始化
17    static {
18        //配置io线程
19        IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
20                .setIoThreadCount(Runtime.getRuntime().availableProcessors())
21                .build();
22        // Http 异步连接池
23        PoolingAsyncClientConnectionManager poolingAsyncClientConnectionManager = new PoolingAsyncClientConnectionManager();
24        poolingAsyncClientConnectionManager.setMaxTotal(200);
25        poolingAsyncClientConnectionManager.setDefaultMaxPerRoute(200);
26        poolingAsyncClientConnectionManager.setValidateAfterInactivity(TimeValue.ofMinutes(5));
27        // HttpAsyncClient
28        closeableHttpAsyncClient = HttpAsyncClients.custom()
29                .setIOReactorConfig(ioReactorConfig)
30                .setConnectionManager(poolingAsyncClientConnectionManager)
31                .build();
32        // 运行
33        closeableHttpAsyncClient.start();
34    }
35
36    /**
37     * 获取 HttpAsyncclient 对象
38     *
39     * @return CloseableHttpAsyncClient
40     */
41    public static CloseableHttpAsyncClient getHttpclient() {
42        return closeableHttpAsyncClient;
43    }
44
45}

2、基本操作示例

 1import club.mydlq.utils.HttpClientAsycnUtil;
 2import lombok.extern.slf4j.Slf4j;
 3import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
 4import org.apache.hc.client5.http.async.methods.SimpleHttpRequests;
 5import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
 6import org.apache.hc.core5.concurrent.FutureCallback;
 7import org.apache.hc.core5.http.HttpHost;
 8import org.apache.hc.core5.http.Method;
 9import java.util.concurrent.ExecutionException;
10import java.util.concurrent.Future;
11
12@Slf4j
13public class BaseExample {
14
15    /**
16     * Http 异步请求
17     */
18    public static void asyncRequest() {
19        try {
20            HttpHost httpHost = new HttpHost("http","localhost",8080);
21            SimpleHttpRequest simpleHttpRequest = SimpleHttpRequests.create(Method.GET,httpHost,"/base/get?name=test&sex=man");
22            final Future<SimpleHttpResponse> future = HttpClientAsycnUtil.getHttpclient()
23                    .execute(simpleHttpRequest, new FutureCallback<SimpleHttpResponse>() {
24
25                        @Override
26                        public void completed(final SimpleHttpResponse response) {
27                            log.info(response.toString());
28                        }
29
30                        @Override
31                        public void failed(final Exception ex) {
32                            log.error("执行请求失败:", ex);
33                        }
34
35                        @Override
36                        public void cancelled() {
37                            log.info("取消请求");
38                        }
39
40                    });
41            String responseBody = future.get().getBody().getBodyText();
42            log.info(responseBody);
43        } catch (ExecutionException | InterruptedException e) {
44            log.error("", e);
45            Thread.currentThread().interrupt();
46        }
47    }
48
49    /** 测试 Main 方法 */
50    public static void main(final String[] args) {
51        asyncRequest();
52    }
53
54}

---END---


  !版权声明:本博客内容均为原创,每篇博文作为知识积累,写博不易,转载请注明出处。