pom依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.15</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore-nio</artifactId>
<version>4.4.14</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.apache.httpcomponents</groupId>-->
<!-- <artifactId>httpasyncclient</artifactId>-->
<!-- <version>4.1.2</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1.1</version>
</dependency>
工具类代码
package com.mt.utils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.util.CollectionUtils;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
/**
* author: 15aaa2
* description: client异步请求工具类
* date: 2022/1/5 14:04
*/
public class HttpClientUtils {
private static final CountDownLatch LATCH = new CountDownLatch(1);
private static final Logger LOGGER = Logger.getLogger(HttpClientUtils.class);
/**
* get请求
* @param path 路径
* @param params 参数集合
* @return 返回结果
*/
public static String getRequest(String path, List<NameValuePair> params){
if (path.isEmpty()){
LOGGER.error("path can not be null");
return null;
}
CloseableHttpAsyncClient client = null;
HttpGet get = null;
try {
client = newHttpClient();
client.start();
URIBuilder uri = new URIBuilder(path);
if (!CollectionUtils.isEmpty(params)){
uri.setParameters(params);
}
get = new HttpGet(uri.build());
Future<HttpResponse> execute = client.execute(get, new Back(LATCH));
HttpResponse response = execute.get();
HttpEntity entity = response.getEntity();
// String s = EntityUtils.toString(entity);
// System.out.println("==========");
// System.out.println(s);
// System.out.println("==========");
return EntityUtils.toString(entity);
}catch (Exception e){
e.printStackTrace();
}finally {
if (get != null){
get.releaseConnection();
}
if (client!=null){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* post请求
* @param path 路径
* @param entity JSON对象参数
* @param params 普通参数
* @return 返回结果
*/
public static String postRequest(String path, StringEntity entity,List<NameValuePair> params){
CloseableHttpAsyncClient client = null;
HttpPost post = null;
try {
client = newHttpClient();
client.start();
URIBuilder uri = new URIBuilder(path);
if (!CollectionUtils.isEmpty(params)){
uri.setParameters(params);
}
post = new HttpPost(uri.build());
post.addHeader("Content-Type", "application/json");
post.addHeader("Accept", "application/json");
if (entity != null){
post.setEntity(entity);
}
Future<HttpResponse> execute = client.execute(post, new Back(LATCH));
HttpResponse response = execute.get();
if (response.getStatusLine().getStatusCode() != 200){
System.out.println("请求失败");
return null;
}
return EntityUtils.toString(response.getEntity());
}catch (Exception e){
e.printStackTrace();
}finally {
if (post!=null){
post.releaseConnection();
}
if (client!=null){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 创建httpClient实例
* @return 返回CloseableHttpAsyncClient
*/
private static CloseableHttpAsyncClient newHttpClient(){
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(50000)
.setSocketTimeout(50000)
.setConnectionRequestTimeout(1000)
.build();
//配置io线程
IOReactorConfig ioReactorConfig = IOReactorConfig.custom().
setIoThreadCount(Runtime.getRuntime().availableProcessors())
.setSoKeepAlive(true)
.build();
//设置连接池大小
ConnectingIOReactor ioReactor=null;
try {
ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
} catch (IOReactorException e) {
e.printStackTrace();
}
PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor);
connManager.setMaxTotal(100);
connManager.setDefaultMaxPerRoute(100);
CloseableHttpAsyncClient client = HttpAsyncClients.custom().
setConnectionManager(connManager)
.setDefaultRequestConfig(requestConfig)
.build();
return client;
}
static class Back implements FutureCallback<HttpResponse>{
private CountDownLatch countDownLatch;
Back(CountDownLatch countDownLatch){
this.countDownLatch = countDownLatch;
}
@Override
public void completed(HttpResponse result) {
// System.out.println("-------------");
// System.out.println(result.getEntity());
// System.out.println("-------------");
LATCH.countDown();
}
@Override
public void failed(Exception ex) {
LATCH.countDown();
}
@Override
public void cancelled() {
LATCH.countDown();
}
}
}