import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.http.MediaType;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Slf4j
public class HttpUtil {
private final static RequestConfig REQUEST_CONFIG;
public final static PoolingHttpClientConnectionManager CONNECTION_MANAGER;
private final static HttpClientBuilder HTTP_CLIENT_NO_POOL_BUILDER;
private final static HttpClientBuilder HTTP_CLIENT_POOL_BUILDER;
private final static int CONNECT_TIMEOUT = 1000;
private final static int SOCKET_TIMEOUT = 10000;
private final static int REQUEST_TIMEOUT = 10000;
private final static String COOKIE_HEADER_NAME = "Cookie";
static {
Registry<ConnectionSocketFactory> socketFactoryRegistry = null;
SSLContext sslContext = null;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true).build();
socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE))
.build();
} catch (Exception e) {
log.info("信任ssl初始化异常:{}", ExceptionUtils.getStackTrace(e));
}
CONNECTION_MANAGER = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CONNECTION_MANAGER.setMaxTotal(200);
CONNECTION_MANAGER.setDefaultMaxPerRoute(100);
CONNECTION_MANAGER.setValidateAfterInactivity(60000);
REQUEST_CONFIG = RequestConfig.custom()
.setConnectionRequestTimeout(REQUEST_TIMEOUT)
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.build();
HTTP_CLIENT_NO_POOL_BUILDER = HttpClients.custom()
.setDefaultRequestConfig(REQUEST_CONFIG)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setSSLContext(sslContext)
.disableAutomaticRetries();
HTTP_CLIENT_POOL_BUILDER = HttpClients.custom()
.setDefaultRequestConfig(REQUEST_CONFIG)
.setConnectionManager(CONNECTION_MANAGER)
.disableAutomaticRetries();
}
public static HttpUtilResponse doPostJson(String url, Map<String, List<String>> urlParam, Object jsonBody, Map<String, String> headers, List<Cookie> cookies) {
HttpPost httpPost = new HttpPost(setUrlParamToUrl(url, urlParam));
CloseableHttpResponse response = null;
setHeaders(httpPost, headers);
setCookies(httpPost, cookies);
long start = System.currentTimeMillis();
try {
String jsonParam = JSON.toJSONString(jsonBody);
StringEntity stringEntity = new StringEntity(jsonParam);
stringEntity.setContentType(MediaType.APPLICATION_JSON_VALUE);
stringEntity.setContentEncoding(StandardCharsets.UTF_8.name());
httpPost.setEntity(stringEntity);
CloseableHttpClient httpClient = getTrustedHttpclient();
response = httpClient.execute(httpPost);
String result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
log.info("url:{},urlParam:{},jsonBody:{},headers:{},cookies:{},耗时;{},reslut:{}", url,
JSON.toJSONString(urlParam), jsonParam, JSON.toJSONString(headers), JSON.toJSONString(cookies),
System.currentTimeMillis() - start, result);
return new HttpUtilResponse(httpRequestIsSuccess(response.getStatusLine()), result);
} catch (Exception e) {
log.error("url:{},异常:{}", url, ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
log.error("HttpUtil还回连接池异常:{}", ExceptionUtils.getStackTrace(e));
}
}
}
return new HttpUtilResponse(false);
}
public static String getUrlParamStr(Map<String, List<String>> urlParam) {
List<NameValuePair> pairs = getMapToPairs(urlParam);
try {
return EntityUtils.toString(new UrlEncodedFormEntity(pairs));
} catch (IOException e) {
log.error("将GET请求的Map参数转换为Url参数异常:{}", ExceptionUtils.getStackTrace(e));
}
return "";
}
private static String setUrlParamToUrl(String url, Map<String, List<String>> urlParam) {
String urlParamStr = getUrlParamStr(urlParam);
return url + (StringUtils.isBlank(urlParamStr) ? "" : ("?" + urlParamStr));
}
private static void setHeaders(HttpRequestBase http, Map<String, String> headers) {
if (null == http) {
return;
}
if (headers == null || headers.isEmpty()) {
return;
}
Set<String> headerNames = headers.keySet();
for (String headerName : headerNames) {
http.setHeader(headerName, headers.get(headerName));
}
}
private static void setCookies(HttpRequestBase http, List<Cookie> cookies) {
if (null == http) {
return;
}
if (cookies == null || cookies.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder();
for (Cookie cookie : cookies) {
sb.append(cookie.getName());
sb.append("=");
sb.append(cookie.getValue());
sb.append("; ");
}
http.setHeader(COOKIE_HEADER_NAME, sb.substring(0, sb.lastIndexOf(";")));
}
public static CloseableHttpClient getTrustedHttpclientNoPool() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
return HTTP_CLIENT_NO_POOL_BUILDER.build();
}
public static CloseableHttpClient getTrustedHttpclient() {
return HTTP_CLIENT_POOL_BUILDER.build();
}
private static boolean httpRequestIsSuccess(StatusLine statusLine) {
return statusLine != null && statusLine.getStatusCode() == HttpStatus.SC_OK;
}
private static List<NameValuePair> getMapToPairs(Map<String, List<String>> map) {
if (map == null || map.size() == 0) {
return new ArrayList<>(0);
}
List<NameValuePair> pairs = new ArrayList<>();
Set<String> keys = map.keySet();
for (String key : keys) {
List<String> values = map.get(key);
if (values == null || values.isEmpty()) {
continue;
}
for (String value : values) {
pairs.add(new BasicNameValuePair(key, value));
}
}
return pairs;
}
static public class HttpUtilResponse {
private Boolean success;
private String result;
public HttpUtilResponse(Boolean success) {
this.success = success;
}
public HttpUtilResponse(Boolean success, String result) {
this.success = success;
this.result = result;
}
public Boolean getSuccess() {
return success;
}
public String getResult() {
return result;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public void setResult(String result) {
this.result = result;
}
}
}
HttpClient工具
最新推荐文章于 2024-05-19 18:51:10 发布