新
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpRequestRetryHandler;
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.methods.HttpUriRequest;
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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;public class HttpClientUtil {public static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);private static PoolingHttpClientConnectionManager connectionManager;private static CloseableHttpClient client;/*** maximum number of connections allowed per host*/private static int maxHostConnections = 100;/*** maximum number of connections allowed overall*/private static int maxTotalConnections = 50;/*** the timeout until a connection is etablished*/private static int connectionTimeOut = 1000;static {connectionManager = new PoolingHttpClientConnectionManager();// 每个路由的最大连接数connectionManager.setDefaultMaxPerRoute(maxHostConnections);// 最大连接数connectionManager.setMaxTotal(maxTotalConnections);// 配置重试策略HttpRequestRetryHandler retryHandler = (exception, executionCount, context) -> {// 如果已经重试了3次,不再重试if (executionCount >= 3) {return false;}// 如果是Socket超时异常,重试if (exception instanceof java.net.SocketTimeoutException) {return true;}return false;};// 配置请求的配置信息,包括连接超时和套接字超时RequestConfig requestConfig = RequestConfig.custom()// 设置连接请求超时(单位:毫秒).setConnectTimeout(connectionTimeOut)// 设置套接字超时(即从服务器读取数据的超时时间,单位:毫秒).setSocketTimeout(connectionTimeOut).build();// 创建 HttpClient 实例,并设置连接管理器和默认请求配置client = HttpClients.custom().setConnectionManager(connectionManager).setRetryHandler(retryHandler).setDefaultRequestConfig(requestConfig).build();}/*** 使用get方式调用** @param url 请求URL* @return 调用得到的字符串*/public static String httpClientGet(String url) throws IOException {HttpGet HttpGet = new HttpGet(url);return getResponseStr(HttpGet);}/*** 发送post或get请求获取响应信息** @param request http请求类型,post或get请求* @return 服务器返回的信息*/public static String getResponseStr(HttpUriRequest request) throws IOException {HttpResponse response = null;try {// 发送请求并获取响应response = client.execute(request);// 检查响应状态码int statusCode = response.getStatusLine().getStatusCode();if (statusCode != 200) {log.error("HttpClient Error: statusCode = {}, uri: {}", statusCode, request.getURI());}// 获取响应体并转换为字符串return EntityUtils.toString(response.getEntity(), "UTF-8");} finally {// 确保响应对象被正确关闭以释放资源if (response != null) {EntityUtils.consume(response.getEntity());}}}/*** 使用post方式调用** @param url 请求URL* @param json 请求参数* @return 调用得到的字符串*/public static String httpPost(String url, Map<String, Object> headerParam, String json) {String s = "";try {// 创建HttpPost对象HttpPost httpPost = new HttpPost(url);// 配置请求头if (headerParam != null && !headerParam.isEmpty()) {for (Entry<String, Object> entry : headerParam.entrySet()) {httpPost.setHeader(entry.getKey(), entry.getValue() != null ? entry.getValue().toString() : "");}}// 设置默认的Content-Type为application/jsonhttpPost.setHeader("Content-Type", "application/json;charset=UTF-8");// 设置请求体if (json != null) {StringEntity stringEntity = new StringEntity(json, StandardCharsets.UTF_8);httpPost.setEntity(stringEntity);}// 发送请求,并获取响应s = getResponseStr(httpPost);} catch (Exception e) {// 记录错误日志log.error("Exception occurred, message: {}", e.getMessage(), e);}return s;}/*** 带有请求头Get请求方式** @param url 请求地址* @param headers 请求头* @return 响应结果*/public static String httpClientGet(String url, HashMap<String, String> headers) throws IOException {HttpGet httpGet = new HttpGet(url);if (headers != null && !headers.isEmpty()) {for (Entry<String, String> entry : headers.entrySet()) {String key = entry.getKey();String value = entry.getValue();httpGet.setHeader(key, StringUtil.null2Str(value));}}return getResponseStr(httpGet);}
}