ecology_dev/src/main/java/aiyh/utils/httpUtil/util/HttpUtils.java

1215 lines
56 KiB
Java
Raw Normal View History

2022-11-22 00:24:17 +08:00
package aiyh.utils.httpUtil.util;
import aiyh.utils.Util;
2022-11-22 14:44:37 +08:00
import aiyh.utils.httpUtil.*;
2022-11-22 00:24:17 +08:00
import aiyh.utils.httpUtil.httpAsync.HttpAsyncThread;
import aiyh.utils.httpUtil.httpAsync.HttpAsyncThreadCallBack;
import aiyh.utils.zwl.common.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import weaver.file.ImageFileManager;
import javax.ws.rs.core.MediaType;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/31 0031 17:16
* http HttpStaticUtils使HttpStaticUtils
*/
public class HttpUtils {
2022-11-22 14:44:37 +08:00
public static final String JSON_PARAM_KEY = "JSON_PARAM_KEY";
public static final ThreadLocal<HttpUtilParamInfo> HTTP_UTIL_PARAM_INFO_THREAD_LOCAL = new ThreadLocal<>();
private static final Logger log = Util.getLogger("http_util");
2022-11-22 00:24:17 +08:00
private final ToolUtil toolUtil = new ToolUtil();
private final GlobalCache globalCache = new GlobalCache();
// 线程池
private final ThreadPoolExecutor executorService;
2022-11-22 14:44:37 +08:00
// 默认编码
private String DEFAULT_ENCODING = "UTF-8";
/**
* basic
*/
private CredentialsProvider credentialsProvider = null;
2022-11-22 00:24:17 +08:00
{
// private final ExecutorService executorService = Executors.newFixedThreadPool(3);
ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
ThreadFactory threadFactory = threadFactoryBuilder.setNameFormat("util-http-pool").build();
executorService = new ThreadPoolExecutor(5, 200, 0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1024),
threadFactory,
new ThreadPoolExecutor.AbortPolicy());
}
public HttpUtils() {
}
public HttpUtils(CredentialsProvider credentialsProvider) {
this.credentialsProvider = credentialsProvider;
}
2022-11-22 14:44:37 +08:00
public HttpUtils(String DEFAULT_ENCODING) {
this.DEFAULT_ENCODING = DEFAULT_ENCODING;
}
public static String urlHandle(String url, Map<String, Object> params) {
if (params == null || params.size() <= 0) {
return url;
}
String serializeParams = serializeParams(params);
String getUrl;
if (!url.contains("?")) {
if (url.endsWith("/")) {
getUrl = url.substring(0, url.length() - 1) + "?" + serializeParams;
} else {
getUrl = url + "?" + serializeParams;
}
} else {
if (url.endsWith("?")) {
getUrl = url + serializeParams;
} else {
getUrl = url + "&" + serializeParams;
}
}
return getUrl;
}
private static String serializeParams(Map<String, Object> params) {
if (params != null && params.size() > 0) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, Object> entry : params.entrySet()) {
builder.append("&");
builder.append(entry.getKey());
builder.append("=");
builder.append(entry.getValue());
}
return removeSeparator(builder);
}
return "";
}
private static String removeSeparator(StringBuilder sqlBuilder) {
String str = sqlBuilder.toString().trim();
String removeSeparator = "&";
if (str.endsWith(removeSeparator)) {
// 如果以分&号结尾,则去除&号
str = str.substring(0, str.length() - 1);
}
if (str.trim().startsWith(removeSeparator)) {
// 如果以&开头,则去除&
str = str.substring(1);
}
return str;
}
2022-11-22 00:24:17 +08:00
public void setCredentialsProvider(CredentialsProvider credentialsProvider) {
this.credentialsProvider = credentialsProvider;
}
public GlobalCache getGlobalCache() {
return globalCache;
}
public void setDEFAULT_ENCODING() {
this.DEFAULT_ENCODING = DEFAULT_ENCODING;
}
public HttpPost getHttpPost(String url) {
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.setRedirectsEnabled(true)
.build();
httpPost.setConfig(requestConfig);
return httpPost;
}
public HttpGet getHttpGet(String url) {
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(10000)
.setConnectionRequestTimeout(10000)
.setRedirectsEnabled(true)
.build();
httpGet.setConfig(requestConfig);
return httpGet;
}
/**
* get
*
* @param url
* @return
* @throws IOException io
*/
public ResponeVo apiGet(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headers = headersHandle(null);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
try {
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setHeard(headers);
httpUtilParamInfo.setUrl(getUrl.trim());
httpUtilParamInfo.setSendDate(new Date());
httpUtilParamInfo.setParams(params);
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
} catch (Exception ignore) {
}
return baseRequest(httpConnection, httpGet);
}
/**
* delete
*
* @param url
* @return
* @throws IOException io
*/
public ResponeVo apiDelete(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headers = headersHandle(null);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
try {
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setHeard(headers);
httpUtilParamInfo.setParams(params);
httpUtilParamInfo.setSendDate(new Date());
httpUtilParamInfo.setUrl(getUrl.trim());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
} catch (Exception ignore) {
}
return baseRequest(httpConnection, httpDelete);
}
/**
* get
*
* @param url
* @param headers
* @return
* @throws IOException io
*/
public ResponeVo apiGet(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headerMap = headersHandle(headers);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
try {
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setHeard(headerMap);
httpUtilParamInfo.setParams(params);
httpUtilParamInfo.setSendDate(new Date());
httpUtilParamInfo.setUrl(getUrl.trim());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
} catch (Exception ignore) {
}
return baseRequest(httpConnection, httpGet);
}
public ResponeVo apiDelete(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headerMap = headersHandle(headers);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
try {
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setHeard(headerMap);
httpUtilParamInfo.setParams(params);
httpUtilParamInfo.setSendDate(new Date());
httpUtilParamInfo.setUrl(getUrl.trim());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
} catch (Exception ignore) {
}
return baseRequest(httpConnection, httpDelete);
}
public ResponeVo apiGet(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
try {
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setHeard(headerMap);
httpUtilParamInfo.setParams(paramsMap);
httpUtilParamInfo.setSendDate(new Date());
httpUtilParamInfo.setUrl(getUrl.trim());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
} catch (Exception ignore) {
}
return baseRequest(httpConnection, httpGet);
}
public ResponeVo apiDelete(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
try {
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setHeard(headerMap);
httpUtilParamInfo.setParams(paramsMap);
httpUtilParamInfo.setSendDate(new Date());
httpUtilParamInfo.setUrl(getUrl.trim());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
} catch (Exception ignore) {
}
return baseRequest(httpConnection, httpDelete);
}
/**
*
*
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public void apiGet(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
try {
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setHeard(headerMap);
httpUtilParamInfo.setParams(paramsMap);
httpUtilParamInfo.setSendDate(new Date());
httpUtilParamInfo.setUrl(getUrl.trim());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
} catch (Exception ignore) {
}
callBackRequest(httpConnection, httpGet, consumer);
}
/**
*
*
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public void apiDelete(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
try {
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setHeard(headerMap);
httpUtilParamInfo.setParams(paramsMap);
httpUtilParamInfo.setSendDate(new Date());
httpUtilParamInfo.setUrl(getUrl.trim());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
} catch (Exception ignore) {
}
callBackRequest(httpConnection, httpDelete, consumer);
}
public ResponeVo apiPost(String url, Map<String, Object> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPost);
}
public ResponeVo apiPut(String url, Map<String, Object> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPut);
}
public ResponeVo apiPost(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPost);
}
public ResponeVo apiPostObject(String url, Object params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPostObject(url, headerMap, params);
return baseRequest(httpConnection, httpPost);
}
public ResponeVo apiPut(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPut);
}
2022-11-22 14:44:37 +08:00
/**
* <h2></h2>
*
* @param url
* @param inputStream
* @param fileKey key
* @param fileName
* @param params
* @param headers
* @return
* @throws IOException IO
*/
2022-11-22 00:24:17 +08:00
public ResponeVo apiUploadFile(String url, InputStream inputStream, String fileKey, String fileName,
Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
2022-11-22 14:44:37 +08:00
MultipartFile multipartFile = new MultipartFile();
multipartFile.setFileName(fileName);
multipartFile.setFileKey(fileKey);
multipartFile.setStream(inputStream);
multipartFile.setFileSize(inputStream.available() / 1024L);
HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap);
return baseRequest(httpConnection, httpPost);
}
/**
* <h2></h2>
*
* @param url
* @param multipartFileList
* @param params
* @param headers
* @return
* @throws IOException Io
*/
public ResponeVo apiUploadFiles(String url, List<MultipartFile> multipartFileList, Map<String, Object> params,
Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = uploadFileByInputStream(url, multipartFileList, paramsMap, headerMap);
2022-11-22 00:24:17 +08:00
return baseRequest(httpConnection, httpPost);
}
2022-11-22 14:44:37 +08:00
/**
* <h2></h2>
*
* @param url
* @param multipartFileList
* @param params
* @param headers
* @return
* @throws IOException Io
*/
public ResponeVo apiPutUploadFiles(String url, List<MultipartFile> multipartFileList, Map<String, Object> params,
Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = uploadFileByInputStreamPut(url, multipartFileList, paramsMap, headerMap);
return baseRequest(httpConnection, httpPut);
}
/**
* <h2></h2>
*
* @param url
* @param inputStream
* @param fileKey key
* @param fileName
* @param params
* @param headers
* @return
* @throws IOException IO
*/
2022-11-22 00:24:17 +08:00
public Future<ResponeVo> apiUploadFileAsync(String url, InputStream inputStream, String fileKey, String fileName,
Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
2022-11-22 14:44:37 +08:00
MultipartFile multipartFile = new MultipartFile();
multipartFile.setFileName(fileName);
multipartFile.setFileKey(fileKey);
multipartFile.setStream(inputStream);
multipartFile.setFileSize(inputStream.available() / 1024L);
HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap);
2022-11-22 00:24:17 +08:00
return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
}
2022-11-22 14:44:37 +08:00
/**
* <h2></h2>
*
* @param url
* @param file
* @param fileKey key
* @param fileName
* @param params
* @param headers
* @return
* @throws IOException IO
*/
2022-11-22 00:24:17 +08:00
public ResponeVo apiUploadFile(String url, File file, String fileKey, String fileName,
Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = uploadFileByInputStream(url, file, fileKey, fileName, paramsMap, headerMap);
return baseRequest(httpConnection, httpPost);
}
2022-11-22 14:44:37 +08:00
/**
* <h2>ImageFileId</h2>
*
* @param url
* @param id ID
* @param fileKey key
* @param fileName
* @param params
* @param headers
* @return
* @throws IOException IO
*/
2022-11-22 00:24:17 +08:00
public ResponeVo apiUploadFileById(String url, int id, String fileKey, String fileName,
Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
InputStream inputStream = ImageFileManager.getInputStreamById(id);
2022-11-22 14:44:37 +08:00
MultipartFile multipartFile = new MultipartFile();
multipartFile.setFileName(fileName);
multipartFile.setFileKey(fileKey);
multipartFile.setStream(inputStream);
multipartFile.setFileSize(inputStream.available() / 1024L);
HttpPost httpPost = uploadFileByInputStream(url, Collections.singletonList(multipartFile), paramsMap, headerMap);
2022-11-22 00:24:17 +08:00
return baseRequest(httpConnection, httpPost);
}
/**
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public void apiPost(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
callBackRequest(httpConnection, httpPost, consumer);
}
public ResponeVo apiPost(String url, Map<String, Object> params, Map<String, String> headers, Function<CloseableHttpResponse, ResponeVo> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return callBackRequest(httpConnection, httpPost, consumer);
}
public ResponeVo apiPost(String url, Map<String, Object> params, Map<String, String> headers, BiFunction<Map<String, Object>, CloseableHttpResponse, ResponeVo> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return callBackRequest(paramsMap, httpConnection, httpPost, consumer);
}
/**
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
public void apiPut(String url, Map<String, Object> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
callBackRequest(httpConnection, httpPut, consumer);
}
private void callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpResponse response = null;
try {
response = httpClient.execute(request);
consumer.accept(response);
} catch (Exception e) {
toolUtil.writeErrorLog(" http调用失败:" + e);
throw e;
} finally {
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove();
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
}
}
private ResponeVo callBackRequest(CloseableHttpClient httpClient, HttpUriRequest request, Function<CloseableHttpResponse, ResponeVo> consumer) throws IOException {
CloseableHttpResponse response = null;
ResponeVo apply = null;
try {
response = httpClient.execute(request);
apply = consumer.apply(response);
} catch (Exception e) {
toolUtil.writeErrorLog(" http调用失败:" + e);
throw e;
} finally {
HttpUtilParamInfo httpUtilParamInfo = HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.get();
if (httpUtilParamInfo == null) {
httpUtilParamInfo = new HttpUtilParamInfo();
}
httpUtilParamInfo.setResponse(apply);
httpUtilParamInfo.setResponseDate(new Date());
try {
log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(),
JSONObject.toJSONString(httpUtilParamInfo,
SerializerFeature.PrettyFormat,
SerializerFeature.WriteDateUseDateFormat)));
} catch (Exception ignore) {
}
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove();
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
}
return apply;
}
private ResponeVo callBackRequest(Map<String, Object> requestParam, CloseableHttpClient httpClient, HttpUriRequest request, BiFunction<Map<String, Object>, CloseableHttpResponse, ResponeVo> consumer) throws IOException {
CloseableHttpResponse response = null;
ResponeVo apply = null;
try {
response = httpClient.execute(request);
apply = consumer.apply(requestParam, response);
} catch (Exception e) {
toolUtil.writeErrorLog(" http调用失败:" + e);
throw e;
} finally {
HttpUtilParamInfo httpUtilParamInfo = HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.get();
if (httpUtilParamInfo == null) {
httpUtilParamInfo = new HttpUtilParamInfo();
}
httpUtilParamInfo.setResponse(apply);
httpUtilParamInfo.setResponseDate(new Date());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove();
try {
log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(),
JSONObject.toJSONString(httpUtilParamInfo,
SerializerFeature.PrettyFormat,
SerializerFeature.WriteDateUseDateFormat)));
} catch (Exception ignore) {
}
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
}
return apply;
}
public ResponeVo baseRequest(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException {
ResponeVo responeVo = new ResponeVo();
CloseableHttpResponse response = null;
HttpUtilParamInfo httpUtilParamInfo = HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.get();
if (httpUtilParamInfo == null) {
httpUtilParamInfo = new HttpUtilParamInfo();
}
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.remove();
try {
response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
Header[] allHeaders = response.getAllHeaders();
Locale locale = response.getLocale();
responeVo.setLocale(locale);
responeVo.setAllHeaders(allHeaders);
responeVo.setEntityString(EntityUtils.toString(entity, DEFAULT_ENCODING));
responeVo.setCode(response.getStatusLine().getStatusCode());
httpUtilParamInfo.setResponse(responeVo);
httpUtilParamInfo.setResponseDate(new Date());
try {
log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(),
JSONObject.toJSONString(httpUtilParamInfo,
SerializerFeature.PrettyFormat,
SerializerFeature.WriteDateUseDateFormat)));
} catch (Exception ignore) {
}
} catch (Exception e) {
toolUtil.writeErrorLog(" http调用失败:" + Util.getErrString(e));
try {
httpUtilParamInfo.setResponseDate(new Date());
log.info(Util.logStr("url [{}] request info : [\n{}\n];", httpUtilParamInfo.getUrl(),
JSONObject.toJSONString(httpUtilParamInfo,
SerializerFeature.PrettyFormat,
SerializerFeature.WriteDateUseDateFormat)));
} catch (Exception ignore) {
}
throw e;
} finally {
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
}
return responeVo;
}
/**
* get
*
* @param url
* @return
* @throws IOException io
*/
public Future<ResponeVo> asyncApiGet(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headers = headersHandle(null);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING));
}
/**
* delete
*
* @param url
* @return
* @throws IOException io
*/
public Future<ResponeVo> asyncApiDelete(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headers = headersHandle(null);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING));
}
/**
* get
*
* @param url
* @param headers
* @return
* @throws IOException io
*/
public Future<ResponeVo> asyncApiGet(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headerMap = headersHandle(headers);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING));
}
public Future<ResponeVo> asyncApiDelete(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> params = paramsHandle(null);
String getUrl = urlHandle(url, params);
Map<String, String> headerMap = headersHandle(headers);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING));
}
public Future<ResponeVo> asyncApiGet(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpGet, DEFAULT_ENCODING));
}
public Future<ResponeVo> asyncApiDelete(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return executorService.submit(new HttpAsyncThread(httpConnection, httpDelete, DEFAULT_ENCODING));
}
/**
*
*
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
2022-11-22 14:44:37 +08:00
public void asyncApiGet(String url, Map<String, Object> params, Map<String, String> headers, Consumer<ResponeVo> consumer) throws IOException {
2022-11-22 00:24:17 +08:00
Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
2022-11-22 14:44:37 +08:00
HttpAsyncThreadCallBack command = new HttpAsyncThreadCallBack(httpConnection, httpGet, consumer);
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setParams(paramsMap);
httpUtilParamInfo.setUrl(url);
httpUtilParamInfo.setHeard(headerMap);
httpUtilParamInfo.setSendDate(new Date());
command.setHttpUtilParamInfo(httpUtilParamInfo);
executorService.execute(command);
2022-11-22 00:24:17 +08:00
}
/**
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
2022-11-22 14:44:37 +08:00
public void asyncApiDelete(String url, Map<String, Object> params, Map<String, String> headers, Consumer<ResponeVo> consumer) throws IOException {
2022-11-22 00:24:17 +08:00
Map<String, Object> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
2022-11-22 14:44:37 +08:00
HttpAsyncThreadCallBack command = new HttpAsyncThreadCallBack(httpConnection, httpDelete, consumer);
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setParams(paramsMap);
httpUtilParamInfo.setUrl(url);
httpUtilParamInfo.setHeard(headerMap);
httpUtilParamInfo.setSendDate(new Date());
command.setHttpUtilParamInfo(httpUtilParamInfo);
executorService.execute(command);
2022-11-22 00:24:17 +08:00
}
public Future<ResponeVo> asyncApiPost(String url, Map<String, Object> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
}
public Future<ResponeVo> asyncApiPut(String url, Map<String, Object> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING));
}
public Future<ResponeVo> asyncApiPost(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
}
public Future<ResponeVo> asyncApiPut(String url, Map<String, Object> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPut, DEFAULT_ENCODING));
}
/**
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
2022-11-22 14:44:37 +08:00
public void asyncApiPost(String url, Map<String, Object> params, Map<String, String> headers, Consumer<ResponeVo> consumer) throws IOException {
2022-11-22 00:24:17 +08:00
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
2022-11-22 14:44:37 +08:00
HttpAsyncThreadCallBack command = new HttpAsyncThreadCallBack(httpConnection, httpPost, consumer);
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setParams(paramsMap);
httpUtilParamInfo.setUrl(url);
httpUtilParamInfo.setHeard(headerMap);
httpUtilParamInfo.setSendDate(new Date());
command.setHttpUtilParamInfo(httpUtilParamInfo);
executorService.execute(command);
2022-11-22 00:24:17 +08:00
}
/**
* @param url
* @param params
* @param headers
* @param consumer
* @throws IOException io
*/
2022-11-22 14:44:37 +08:00
public void asyncApiPut(String url, Map<String, Object> params, Map<String, String> headers, Consumer<ResponeVo> consumer) throws IOException {
2022-11-22 00:24:17 +08:00
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url, this.credentialsProvider);
Map<String, Object> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
2022-11-22 14:44:37 +08:00
HttpAsyncThreadCallBack command = new HttpAsyncThreadCallBack(httpConnection, httpPut, consumer);
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setParams(paramsMap);
httpUtilParamInfo.setUrl(url);
httpUtilParamInfo.setHeard(headerMap);
httpUtilParamInfo.setSendDate(new Date());
command.setHttpUtilParamInfo(httpUtilParamInfo);
executorService.execute(command);
2022-11-22 00:24:17 +08:00
}
private HttpPost handleHttpPostObject(String url, Map<String, String> headerMap, Object paramsMap) throws UnsupportedEncodingException {
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setParams(paramsMap);
httpUtilParamInfo.setUrl(url);
httpUtilParamInfo.setHeard(headerMap);
httpUtilParamInfo.setSendDate(new Date());
String contentType = "";
HttpPost httpPost = new HttpPost(url.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
if ("Content-Type".equalsIgnoreCase(entry.getKey())) {
contentType = entry.getValue();
}
}
httpUtilParamInfo.setContentType(contentType);
if (!Strings.isNullOrEmpty(contentType) && contentType.equalsIgnoreCase(MediaType.APPLICATION_JSON)) {
StringEntity stringEntity;
stringEntity = new StringEntity(JSON.toJSONString(paramsMap), DEFAULT_ENCODING);
httpPost.setEntity(stringEntity);
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
return httpPost;
}
Map<String, Object> params = (Map<String, Object>) paramsMap;
if (Strings.isNullOrEmpty(contentType)) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, Object> entry : params.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
}
httpPost.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE);
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
} else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, Object> entry : params.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
// } else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) {
} else {
StringEntity stringEntity;
if (params.containsKey(JSON_PARAM_KEY)) {
stringEntity = new StringEntity(JSON.toJSONString(params.get(JSON_PARAM_KEY)));
} else {
stringEntity = new StringEntity(JSON.toJSONString(params), DEFAULT_ENCODING);
}
httpPost.setEntity(stringEntity);
}
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
return httpPost;
}
private HttpPost handleHttpPost(String url, Map<String, String> headerMap, Map<String, Object> paramsMap) throws UnsupportedEncodingException {
return handleHttpPostObject(url, headerMap, paramsMap);
}
2022-11-22 14:44:37 +08:00
/**
* <h2></h2>
*
* @param url
* @param multipartFileList
* @param params
* @param headers
* @return httpPost
*/
private HttpPost uploadFileByInputStream(String url, List<MultipartFile> multipartFileList,
Map<String, Object> params, Map<String, String> headers) {
log.info(Util.logStr("start request : url is [{}]" +
"", url));
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setParams(params);
httpUtilParamInfo.setUrl(url);
httpUtilParamInfo.setHeard(headers);
httpUtilParamInfo.setSendDate(new Date());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
2022-11-22 00:24:17 +08:00
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(StandardCharsets.UTF_8);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
2022-11-22 14:44:37 +08:00
Long totalSize = 0L;
for (MultipartFile multipartFile : multipartFileList) {
2022-11-23 10:10:06 +08:00
log.info(Util.logStr("add file: fileName => [{}], fileKey => [{}], fileSize => [{}]kb",
2022-11-22 14:44:37 +08:00
multipartFile.getFileName(), multipartFile.getFileKey(), multipartFile.getFileSize()));
totalSize += multipartFile.getFileSize();
builder.addBinaryBody(multipartFile.getFileKey(), multipartFile.getStream(), ContentType.MULTIPART_FORM_DATA, multipartFile.getFileName());
}
2022-11-23 10:10:06 +08:00
log.info("total file size: [" + totalSize + "]kb");
2022-11-22 00:24:17 +08:00
ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8);
for (Map.Entry<String, Object> param : params.entrySet()) {
StringBody stringBody = new StringBody(String.valueOf(param.getValue()), contentType);
builder.addPart(param.getKey(), stringBody);
}
HttpPost httpPost = new HttpPost(url.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
if ("Content-Type".equalsIgnoreCase(entry.getKey())) {
continue;
}
httpPost.setHeader(entry.getKey(), entry.getValue());
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
return httpPost;
}
2022-11-22 14:44:37 +08:00
/**
* <h2></h2>
*
* @param url
* @param multipartFileList
* @param params
* @param headers
* @return httpPost
*/
private HttpPut uploadFileByInputStreamPut(String url, List<MultipartFile> multipartFileList,
Map<String, Object> params, Map<String, String> headers) {
log.info(Util.logStr("start request : url is [{}]" +
"", url));
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setParams(params);
httpUtilParamInfo.setUrl(url);
httpUtilParamInfo.setHeard(headers);
httpUtilParamInfo.setSendDate(new Date());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(StandardCharsets.UTF_8);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
Long totalSize = 0L;
for (MultipartFile multipartFile : multipartFileList) {
2022-11-23 10:10:06 +08:00
log.info(Util.logStr("add file: fileName => [{}], fileKey => [{}], fileSize => [{}]kb",
2022-11-22 14:44:37 +08:00
multipartFile.getFileName(), multipartFile.getFileKey(), multipartFile.getFileSize()));
totalSize += multipartFile.getFileSize();
builder.addBinaryBody(multipartFile.getFileKey(), multipartFile.getStream(), ContentType.MULTIPART_FORM_DATA, multipartFile.getFileName());
}
2022-11-23 10:10:06 +08:00
log.info("total file size: [" + totalSize + "]kb");
2022-11-22 14:44:37 +08:00
ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8);
for (Map.Entry<String, Object> param : params.entrySet()) {
StringBody stringBody = new StringBody(String.valueOf(param.getValue()), contentType);
builder.addPart(param.getKey(), stringBody);
}
HttpPut httpPut = new HttpPut(url.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
if ("Content-Type".equalsIgnoreCase(entry.getKey())) {
continue;
}
httpPut.setHeader(entry.getKey(), entry.getValue());
}
HttpEntity entity = builder.build();
httpPut.setEntity(entity);
return httpPut;
}
private HttpPost uploadFileByInputStream(String url, File file, String fileKey, String fileName,
Map<String, Object> params, Map<String, String> headers) {
2022-11-22 00:24:17 +08:00
log.info(Util.logStr("start request : url is [{}], params is [{}], header is [{}]; fileKey is [{}], fileName is [{}]" +
"", url, JSON.toJSONString(params), JSON.toJSONString(headers), fileKey, fileName));
2022-11-22 14:44:37 +08:00
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setParams(params);
httpUtilParamInfo.setUrl(url);
httpUtilParamInfo.setHeard(headers);
httpUtilParamInfo.setSendDate(new Date());
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
2022-11-22 00:24:17 +08:00
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody(fileKey, file, ContentType.MULTIPART_FORM_DATA, fileName);
for (Map.Entry<String, Object> param : params.entrySet()) {
StringBody stringBody = new StringBody(String.valueOf(param.getValue()), ContentType.MULTIPART_FORM_DATA);
builder.addPart(param.getKey(), stringBody);
}
HttpPost httpPost = new HttpPost(url.trim());
for (Map.Entry<String, String> entry : headers.entrySet()) {
if ("Content-Type".equalsIgnoreCase(entry.getKey())) {
continue;
}
httpPost.setHeader(entry.getKey(), entry.getValue());
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
return httpPost;
}
private HttpPut handleHttpPut(String url, Map<String, String> headerMap, Map<String, Object> paramsMap) throws UnsupportedEncodingException {
HttpUtilParamInfo httpUtilParamInfo = new HttpUtilParamInfo();
httpUtilParamInfo.setParams(paramsMap);
httpUtilParamInfo.setUrl(url);
httpUtilParamInfo.setHeard(headerMap);
httpUtilParamInfo.setSendDate(new Date());
String contentType = "";
HttpPut httpPut = new HttpPut(url.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPut.setHeader(entry.getKey(), entry.getValue());
if ("Content-Type".equalsIgnoreCase(entry.getKey())) {
contentType = entry.getValue();
}
}
if (Strings.isNullOrEmpty(contentType)) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
}
httpPut.setHeader("Content-Type", HttpArgsType.DEFAULT_CONTENT_TYPE);
httpPut.setEntity(new UrlEncodedFormEntity(nvps));
} else if (contentType.toUpperCase().startsWith(HttpArgsType.X_WWW_FORM_URLENCODED.toUpperCase())) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
}
httpPut.setEntity(new UrlEncodedFormEntity(nvps));
} else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) {
StringEntity stringEntity = new StringEntity(JSON.toJSONString(paramsMap), DEFAULT_ENCODING);
httpPut.setEntity(stringEntity);
}
HTTP_UTIL_PARAM_INFO_THREAD_LOCAL.set(httpUtilParamInfo);
return httpPut;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
toolUtil.writeErrorLog(e.getLocalizedMessage() + "\n" + e);
}
return total.toString();
}
public Map<String, String> headersHandle(Map<String, String> headers) {
Map<String, String> map = new HashMap<>();
if (headers != null && headers.size() > 0) {
if (globalCache.header != null && globalCache.header.size() > 0) {
map.putAll(globalCache.header);
}
map.putAll(headers);
} else {
map.putAll(globalCache.header);
}
return map;
}
public Map<String, Object> paramsHandle(Map<String, Object> params) {
Map<String, Object> map = new HashMap<>();
if (params != null && params.size() > 0) {
if (globalCache.paramMap != null && globalCache.paramMap.size() > 0) {
map.putAll(globalCache.paramMap);
}
map.putAll(params);
} else {
map.putAll(globalCache.paramMap);
}
return map;
}
}