io.github.linmoure.utils.HttpClientPool Maven / Gradle / Ivy
package io.github.linmoure.utils;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import io.github.linmoure.constants.Constants;
import io.github.linmoure.constants.HTTPConstants;
import io.github.linmoure.dto.KeyValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
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.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.FormBodyPartBuilder;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static java.nio.charset.StandardCharsets.UTF_8;
@Slf4j
public class HttpClientPool {
private static CloseableHttpClient httpClient = null;
public static final String CONNECT_TIME_OUT = "http.client.connect.timeout";
private static HttpClient initHttpClient() {
if (null == httpClient) {
Integer timeout = Integer.parseInt(System.getProperty(CONNECT_TIME_OUT, "5000"));
Registry socketFactoryRegistry = RegistryBuilder.create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", SSLConnectionSocketFactory.getSocketFactory()).build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
connectionManager.setMaxTotal(210);
connectionManager.setDefaultMaxPerRoute(30);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
HttpRequestRetryHandler retryHandler = new StandardHttpRequestRetryHandler();
httpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).setRetryHandler(retryHandler).build();
return httpClient;
} else {
return httpClient;
}
}
public static String getResult(String url) {
return getResult(url, null, null, null);
}
public static String getResult(String url, Map params, Map header) {
return getResult(url, params, null, header);
}
public static String getResult(String url, HttpEntity httpEntity, Map header) {
return getResult(url, null, httpEntity, header);
}
public static String getResult(String url, Map params, HttpEntity httpEntity, Map header) {
HttpClient httpClient = initHttpClient();
String resultJson = null;
URI build = null;
try {
URIBuilder uri = new URIBuilder(url);
if (!CollectionUtils.isEmpty(params)) {
List parameter = Lists.newArrayList();
params.forEach((k, v) -> {
parameter.add(new NameValuePair() {
@Override
public String getName() {
return k;
}
@Override
public String getValue() {
return v;
}
});
});
uri.addParameters(parameter);
log.info("params:{}", JSON.toJSONString(params));
}
build = uri.build();
HttpResponse response;
if (httpEntity != null) {
io.github.linmoure.utils.HttpGet httpGet = (io.github.linmoure.utils.HttpGet) createHttpRequest(build, HTTPConstants.GET, Constants.BOOLEAN_TRUE);
httpGet.setEntity(httpEntity);
if (!CollectionUtils.isEmpty(header)) {
header.forEach(httpGet::setHeader);
}
response = httpClient.execute(httpGet);
} else {
org.apache.http.client.methods.HttpGet httpGet = (org.apache.http.client.methods.HttpGet) createHttpRequest(build, HTTPConstants.GET);
if (!CollectionUtils.isEmpty(header)) {
header.forEach(httpGet::setHeader);
}
response = httpClient.execute(httpGet);
}
resultJson = EntityUtils.toString(response.getEntity(), UTF_8);
successResult(build, resultJson);
} catch (Exception e) {
errorResult(build == null ? url : build, e);
}
return resultJson;
}
public static String getPutResult(String url) {
return getPutResult(url, null, null, null);
}
public static String getPutResult(String url, Map params) {
return getPutResult(url, params, null, null);
}
public static String getPutResult(String url, HttpEntity httpEntity) {
return getPutResult(url, null, httpEntity, null);
}
public static String getPutResult(String url, HttpEntity httpEntity, Map header) {
return getPutResult(url, null, httpEntity, header);
}
public static String getPutResult(String url, Map params, HttpEntity httpEntity, Map header) {
HttpClient httpClient = initHttpClient();
String resultJson = null;
URI build = null;
try {
URIBuilder uri = new URIBuilder(url);
if (!CollectionUtils.isEmpty(params)) {
List parameter = Lists.newArrayList();
params.forEach((k, v) -> {
parameter.add(new NameValuePair() {
@Override
public String getName() {
return k;
}
@Override
public String getValue() {
return v;
}
});
});
uri.addParameters(parameter);
log.info("params{}", JSON.toJSONString(params));
}
build = uri.build();
HttpPut httpPut = (HttpPut) createHttpRequest(build, HTTPConstants.PUT);
if (httpEntity != null) {
httpPut.setEntity(httpEntity);
}
if (!CollectionUtils.isEmpty(header)) {
header.forEach(httpPut::setHeader);
}
HttpResponse response = httpClient.execute(httpPut);
resultJson = EntityUtils.toString(response.getEntity(), UTF_8);
successResult(build, resultJson);
} catch (Exception e) {
errorResult(build == null ? url : build, e);
}
return resultJson;
}
public static String getPostResult(String url) {
return getPostResult(url, null, null, null);
}
public static String getPostResult(String url, Map params) {
return getPostResult(url, params, null, null);
}
public static String getPostResult(String url, HttpEntity httpEntity) {
return getPostResult(url, null, httpEntity, null);
}
public static String getPostResult(String url, HttpEntity httpEntity, Map header) {
return getPostResult(url, null, httpEntity, header);
}
public static String getPostResult(String url, Map params, HttpEntity httpEntity, Map header) {
HttpClient httpClient = initHttpClient();
String resultJson = null;
URI build = null;
try {
URIBuilder uri = new URIBuilder(url);
if (!CollectionUtils.isEmpty(params)) {
List parameter = Lists.newArrayList();
params.forEach((k, v) -> {
parameter.add(new NameValuePair() {
@Override
public String getName() {
return k;
}
@Override
public String getValue() {
return v;
}
});
});
uri.addParameters(parameter);
log.info("params{}", JSON.toJSONString(params));
}
build = uri.build();
HttpPost httpPost = (HttpPost) createHttpRequest(build, HTTPConstants.POST);
if (httpEntity != null) {
httpPost.setEntity(httpEntity);
}
if (!CollectionUtils.isEmpty(header)) {
header.forEach(httpPost::setHeader);
}
HttpResponse response = httpClient.execute(httpPost);
resultJson = EntityUtils.toString(response.getEntity(), UTF_8);
successResult(build, resultJson);
} catch (Exception e) {
errorResult(build == null ? url : build, e);
}
return resultJson;
}
public static String getDeleteResult(String url) {
return getDeleteResult(url, null, null);
}
public static String getDeleteResult(String url, Map header) {
return getDeleteResult(url, null, header);
}
public static String getDeleteResult(String url, Map params, Map header) {
HttpClient httpClient = initHttpClient();
String resultJson = null;
URI build = null;
try {
URIBuilder uri = new URIBuilder(url);
if (!CollectionUtils.isEmpty(params)) {
List parameter = Lists.newArrayList();
params.forEach((k, v) -> {
parameter.add(new NameValuePair() {
@Override
public String getName() {
return k;
}
@Override
public String getValue() {
return v;
}
});
});
uri.addParameters(parameter);
log.info("params:{}", JSON.toJSONString(params));
}
build = uri.build();
HttpDelete httpDelete = (HttpDelete) createHttpRequest(build, HTTPConstants.DELETE);
if (!CollectionUtils.isEmpty(header)) {
header.forEach(httpDelete::setHeader);
}
HttpResponse response = httpClient.execute(httpDelete);
resultJson = EntityUtils.toString(response.getEntity(), UTF_8);
successResult(build, resultJson);
} catch (Exception e) {
errorResult(build == null ? url : build, e);
}
return resultJson;
}
public static HttpRequestBase createHttpRequest(URI uri, String method, Boolean... sendGetBody) {
HttpRequestBase result;
if (method.equals(HTTPConstants.POST)) {
result = new HttpPost(uri);
} else if (method.equals(HTTPConstants.GET)) {
if (sendGetBody != null && sendGetBody.length > 0 && Boolean.TRUE.equals(sendGetBody[0])) {
result = new io.github.linmoure.utils.HttpGet(uri);
} else {
result = new org.apache.http.client.methods.HttpGet(uri);
}
} else if (method.equals(HTTPConstants.PUT)) {
result = new HttpPut(uri);
} else if (method.equals(HTTPConstants.HEAD)) {
result = new HttpHead(uri);
} else if (method.equals(HTTPConstants.TRACE)) {
result = new HttpTrace(uri);
} else if (method.equals(HTTPConstants.OPTIONS)) {
result = new HttpOptions(uri);
} else if (method.equals(HTTPConstants.DELETE)) {
result = new HttpDelete(uri);
} else if (method.equals(HTTPConstants.PATCH)) {
result = new HttpPatch(uri);
} else {
throw new IllegalArgumentException("Unexpected method: '" + method + "'");
}
return result;
}
public static HttpEntity getUpHttpEntityEnclosingRequestData(List stringBody, List fileBody, Boolean... doBrowserCompatibleMultipart) {
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setCharset(UTF_8);
if (doBrowserCompatibleMultipart != null && doBrowserCompatibleMultipart.length != 0 && doBrowserCompatibleMultipart[0]) {
multipartEntityBuilder.setLaxMode();
} else {
multipartEntityBuilder.setStrictMode();
}
if (!CollectionUtils.isEmpty(stringBody)) {
stringBody.forEach(v -> {
FormBodyPart formPart = FormBodyPartBuilder.create(v.getName(), new StringBody(v.getValue(), ContentType.create(v.getContentType(), UTF_8))).build();
multipartEntityBuilder.addPart(formPart);
});
}
if (!CollectionUtils.isEmpty(fileBody)) {
fileBody.forEach(v -> {
String paramName = v.getName();
String mimeType = v.getContentType();
String pathname = v.getValue();
File reservedFile = new File(pathname);
ViewableFileBody viewableFileBody = new ViewableFileBody(reservedFile, ContentType.parse(mimeType));
multipartEntityBuilder.addPart(paramName, viewableFileBody);
});
}
return multipartEntityBuilder.build();
}
private static class ViewableFileBody extends FileBody {
private final boolean hideFileData;
public ViewableFileBody(File file, ContentType contentType) {
super(file, contentType);
hideFileData = false;
}
@Override
public void writeTo(final OutputStream out) throws IOException {
if (hideFileData) {
out.write("".getBytes(StandardCharsets.UTF_8));
} else {
super.writeTo(out);
}
}
}
public static void successResult(Object url, Object result) {
log.info("请求路径:{}", url);
log.info("返回结果:{}", result);
}
public static void errorResult(Object url, Throwable e) {
ByteArrayOutputStream text = new ByteArrayOutputStream(200);
e.printStackTrace(new PrintStream(text));
log.info("请求路径:{}", url);
log.info("异常信息:{}", e.getMessage());
log.info("异常详情:{}", text);
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy