package com.springboot.springboottest.utils;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.config.Registry;
import org.apache.hc.core5.http.config.RegistryBuilder;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
public class HttpClientConfig {
private HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
private static final Timeout connectTimeout = Timeout.ofSeconds(10);
private static final Timeout requestTimeout = Timeout.ofSeconds(30);
public static HttpClientConfig custom() {
return new HttpClientConfig();
}
public CloseableHttpClient build() {
//兼容http以及https请求
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", initSSlFactory())
.build();
//适配http以及https请求 通过new创建PoolingHttpClientConnectionManager
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
//https请求 通过PoolingHttpClientConnectionManagerBuilder直级创建
// PoolingHttpClientConnectionManager connManager = PoolingHttpClientConnectionManagerBuilder.create()
// .setSSLSocketFactory(initSSlFactory())
// .setValidateAfterInactivity(TimeValue.ofSeconds(10))
// .setMaxConnPerRoute(maxConnTotal - 1)
// .setMaxConnTotal(maxConnTotal)
// .build();
httpClientBuilder.setConnectionManager(connManager).evictExpiredConnections().evictIdleConnections(TimeValue.ofSeconds(5)).disableAutomaticRetries();
httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(requestTimeout)
.build());
return httpClientBuilder.build();
}
private static SSLConnectionSocketFactory initSSlFactory() {
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{}, null);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
return new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
}
}
package com.springboot.springboottest.utils;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.ToString;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.io.ManagedHttpClientConnectionFactory;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.config.Registry;
import org.apache.hc.core5.http.config.RegistryBuilder;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class HttpUtils {
public static CloseableHttpClient httpClient = HttpClientConfig.custom().build();
public static <T> HttpResponse<T> httpJsonPost(String url, Map<String, String> headers, Object data, Class<T> tClass) throws Exception {
HttpPost httpPost = new HttpPost(url);
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
StringEntity s = new StringEntity(data instanceof String ? (String) data : JSONObject.toJSONString(data)
, ContentType.APPLICATION_JSON);
httpPost.setEntity(s);
return executeHttp(tClass, httpPost);
}
private static <T> HttpResponse<T> executeHttp(Class<T> tClass, ClassicHttpRequest request) throws IOException, ParseException {
try (CloseableHttpResponse response = httpClient.execute(request)) {
int code = response.getCode();
String reasonPhrase = response.getReasonPhrase();
HttpResponse<T> responseData = new HttpResponse<>();
responseData.setRetCode(code);
responseData.setRetMsg(reasonPhrase);
if (code >= HttpStatus.SC_SUCCESS && code < HttpStatus.SC_REDIRECTION) {
String data = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
if (tClass.isAssignableFrom(String.class)) {
responseData.setData((T) data);
} else {
responseData.setData(JSONObject.parseObject(data, tClass));
}
}
EntityUtils.consume(response.getEntity());
return responseData;
}
}
@Data
@ToString
static class HttpResponse<T> {
int retCode;
String retMsg;
T data;
}
}