依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.8</version>
</dependency>
</dependencies>
工具类
package com.jqxx.digtwinresop.module.equipment.data;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.config.SocketConfig;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
* HttpClient 连接池
*
* @author wll
* date 2024/3/25
*/
public class HttpUtil {
private static PoolingHttpClientConnectionManager cm = null;
public static PoolingHttpClientConnectionManager getHttpClientConnectionManager() {
if (cm == null) {
cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(200);
cm.setDefaultMaxPerRoute(20);
SocketConfig config = SocketConfig.custom().setSoTimeout(10000).build();
cm.setDefaultSocketConfig(config);
}
return cm;
}
// 初始化连接池,可用于请求HTTP/HTTPS(信任所有证书)
static {
// 整个连接池最大连接数
cm = getHttpClientConnectionManager();
// 每路由最大连接数,默认值是2
cm.setMaxTotal(200);
cm.setDefaultMaxPerRoute(5);
}
/**
* 表单传参的Post请求
* @param url url
* @param paramMap 请求体
* @param headerMap 请求头
* @return 返回数据
*/
public static String postHttp(String url, Map<String, String> paramMap, Map<String, String> headerMap) {
HttpPost request = new HttpPost(url);
request.addHeader("Content-Type", "application/x-www-form-urlencoded");
if (paramMap != null && paramMap.size() > 0) {
List<NameValuePair> nameValuePairs = covertParams2NVPS(paramMap);
try {
request.setEntity(
new UrlEncodedFormEntity(
nameValuePairs,
StandardCharsets.UTF_8.name()
)
);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
if (headerMap != null) {
for (Entry<String, String> param : headerMap.entrySet()) {
request.addHeader(param.getKey(), param.getValue());
}
}
return doHttp(request);
}
/**
* Json传参的Post请求
* @param url url
* @param requestParam 请求体
* @param headerMap 请求头
* @return 返回数据
*/
public static String jsonPost(String url, Map<String, String> requestParam,Map<String, String> headerMap) { // 接口请求地址
HttpPost httpPost = new HttpPost(url);
// 设置请求头Headers
httpPost.setHeader("Content-Type", "application/json");
if (headerMap != null && headerMap.size() > 0) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
//设置body
if (requestParam != null && requestParam.size() > 0) {
try {
ObjectMapper objectMapper = new ObjectMapper();
String body = objectMapper.writeValueAsString(requestParam);
httpPost.setEntity(new StringEntity(body));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return doHttp(httpPost);
}
/**
* GET请求
* @param url url
* @param headerMap 请求头
* @return 返回参数
*/
public static String getHttp(String url, Map<String, String> headerMap) {
HttpGet request = new HttpGet(url);
if (headerMap != null) {
for (Entry<String, String> param : headerMap.entrySet()) {
request.addHeader(param.getKey(), param.getValue());
}
}
return doHttp(request);
}
// public static String sendHttp() {
// String url = "http://127.0.0.1:49080/admin-api/equipment/task/sy/rwztbt";
// String token = "d4d8c8194b51494e8fb7615460904ff8";
//
// CloseableHttpClient httpClient = HttpClients.createDefault();
// HttpGet httpGet = new HttpGet(url);
//
// // 设置请求头Headers
// httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token);
//
// try {
// HttpResponse response = httpClient.execute(httpGet);
// HttpEntity entity = response.getEntity();
// String responseBody = EntityUtils.toString(entity);
//
// // 处理响应结果
// System.out.println(responseBody);
// return responseBody;
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// } finally {
// try {
// httpClient.close();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
public static List<NameValuePair> covertParams2NVPS(
Map<String, String> params
) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> param : params.entrySet()) pairs.add(
new BasicNameValuePair(param.getKey(), param.getValue())
);
return pairs;
}
private static String doHttp(HttpRequestBase request) {
CloseableHttpClient httpClient = HttpClients
.custom()
.setConnectionManager(cm)
.build();
return doRequest(httpClient, request);
}
private static String doRequest(
CloseableHttpClient httpClient,
HttpRequestBase request
) {
String result = null;
CloseableHttpResponse response = null;
try {
try {
response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity, StandardCharsets.UTF_8.name());
EntityUtils.consume(entity);
} catch (Exception e) {
e.printStackTrace();
}
} finally {
if (null != response) try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
// public static String post(
// String url,
// Map<String, String> paramMap,
// Map<String, String> headerMap
// ) {
// return postHttp(url, paramMap, headerMap);
// }
//
// public static String post(String url, Map<String, String> paramMap) {
// return postHttp(url, paramMap, null);
// }
// Json格式Post请求,但是没使用连接池,注释掉了
// public static String jsonPost(String url, Map<String, String> requestParam,Map<String, String> headerMap) { // 接口请求地址
// CloseableHttpClient httpClient = HttpClients.createDefault();
// HttpPost httpPost = new HttpPost(url);
//
// // 设置请求头Headers
// httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
//
// // 设置请求头Headers
// if (headerMap != null) {
// for (Map.Entry<String, String> entry : headerMap.entrySet()) {
// httpPost.setHeader(entry.getKey(), entry.getValue());
// }
// }
// //设置body
// try {
// ObjectMapper objectMapper = new ObjectMapper();
// String body = objectMapper.writeValueAsString(requestParam);
// httpPost.setEntity(new StringEntity(body));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// try {
// HttpResponse response = httpClient.execute(httpPost);
// HttpEntity entity = response.getEntity();
// return EntityUtils.toString(entity);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// } finally {
// try {
// httpClient.close();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// }
}
测试Demo
public static String demo2(int pageNo, int pageSize, Long id) { // 接口请求地址
String url = "http://127.0.0.1:49080/admin-api/system/auth/login";
Map<String, String> requestParam = new HashMap<>();
requestParam.put("username", "admin");
requestParam.put("password", "admin123");
String token = HttpUtil.jsonPost(url, requestParam, null);
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> map = new HashMap<>();
try {
map = objectMapper.readValue(token, new TypeReference<Map<String, Object>>() {
});
System.out.println(map);
} catch (IOException e) {
e.printStackTrace();
}
String getUrl = "http://127.0.0.1:49080/admin-api/equipment/task/data/page?pageSize=" + pageSize + "&pageNo=" + pageNo + "&id=" + id;
Map tempMap = (LinkedHashMap<String, String>) map.get("data");
Map<String, String> headParam = new HashMap<>();
headParam.put("Authorization", "Bearer " + tempMap.get("accessToken"));
String result = HttpUtil.getHttp(getUrl, headParam);
return result;
}