ecology_maven/aiyh/utils/httpUtil/staticUtil/HttpStaticUtils.java

837 lines
33 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package aiyh.utils.httpUtil.staticUtil;
import aiyh.utils.httpUtil.util.CloseThread;
import com.alibaba.fastjson.JSON;
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.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 aiyh.utils.httpUtil.ExtendedIOUtils;
import aiyh.utils.httpUtil.HttpArgsType;
import aiyh.utils.httpUtil.HttpManager;
import aiyh.utils.httpUtil.ResponeVo;
import aiyh.utils.httpUtil.httpAsync.HttpAsyncThread;
import aiyh.utils.httpUtil.httpAsync.HttpAsyncThreadCallBack;
import aiyh.utils.zwl.common.ToolUtil;
import weaver.file.ImageFileManager;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Consumer;
/**
* @author EBU7-dev1-ayh
* @date 2021/8/31 0031 17:16
* http请求工具
*/
public class HttpStaticUtils {
// 默认编码
public static String DEFAULT_ENCODING = "UTF-8";
private static final ToolUtil toolUtil = new ToolUtil();
// 线程池
public static final ThreadPoolExecutor executorService;
static {
// private final ExecutorService executorService = Executors.newFixedThreadPool(3);
ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
ThreadFactory threadFactory = threadFactoryBuilder.setNameFormat("xxx-pool-%d").build();
executorService = new ThreadPoolExecutor(5, 200, 0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1024),
threadFactory,
new ThreadPoolExecutor.AbortPolicy());
}
public static 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 static 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 static ResponeVo apiGet(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> 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 baseRequest(httpConnection, httpGet);
}
/**
* delete请求
* @param url 请求地址
* @return 请求结果
* @throws IOException io异常
*/
public static ResponeVo apiDelete(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> 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 baseRequest(httpConnection, httpDelete);
}
/**
* get请求
* @param url 请求地址
* @param headers 请求头
* @return 响应结果封装
* @throws IOException io异常
*/
public static ResponeVo apiGet(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> 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 baseRequest(httpConnection, httpGet);
}
/**
* delete请求
* @param url 请求地址
* @param headers 请求头
* @return 请求结果
* @throws IOException io异常
*/
public static ResponeVo apiDelete(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> 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 baseRequest(httpConnection, httpDelete);
}
public static ResponeVo apiGet(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
return baseRequest(httpConnection, httpGet);
}
public static ResponeVo apiDelete(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
return baseRequest(httpConnection, httpDelete);
}
/**
* 回调方法
* @param url 请求地址
* @param params 请求参数
* @param headers 请求头
* @param consumer 回调方法
* @throws IOException io异常
*/
public static void apiGet(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
System.out.println(getUrl);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
callBackRequest(httpConnection, httpGet, consumer);
}
/**
* 回调方法
* @param url 请求地址
* @param params 请求参数
* @param headers 请求头
* @param consumer 回调方法
* @throws IOException io异常
*/
public static void apiDelete(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
callBackRequest(httpConnection, httpDelete, consumer);
}
/**
* post请求
* @param url 请求地址
* @param params 请求参数
* @return 请求结果
* @throws IOException io异常
*/
public static ResponeVo apiPost(String url, Map<String, String> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPost);
}
public static ResponeVo apiPut(String url, Map<String, String> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(null);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPut);
}
/**
* post请求
* @param url 请求地址
* @param params 请求参数
* @param headers 请求头
* @return 请求结果
* @throws IOException io异常
*/
public static ResponeVo apiPost(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPost);
}
public static ResponeVo apiPut(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
return baseRequest(httpConnection, httpPut);
}
public static ResponeVo apiUploadFile(String url,InputStream inputStream, String fileKey,String fileName,
Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = uploadFileByInputStream(url,inputStream, fileKey,fileName, paramsMap, headerMap);
return baseRequest(httpConnection, httpPost);
}
public static ResponeVo apiUploadFile(String url,File file, String fileKey,String fileName,
Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = uploadFileByInputStream(url,file, fileKey,fileName, paramsMap, headerMap);
return baseRequest(httpConnection, httpPost);
}
public static ResponeVo apiUploadFileById(String url,int id, String fileKey,String fileName,
Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
InputStream inputStream = ImageFileManager.getInputStreamById(id);
HttpPost httpPost = uploadFileByInputStream(url,inputStream, fileKey,fileName, paramsMap, headerMap);
return baseRequest(httpConnection, httpPost);
}
public static HttpPost uploadFileByInputStream(String url,InputStream inputStream, String fileKey,String fileName,
Map<String, String> params, Map<String, String> headers){
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody(fileKey,inputStream, ContentType.MULTIPART_FORM_DATA,fileName);
for (Map.Entry<String,String> param : params.entrySet()){
StringBody stringBody = new StringBody(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());
}
httpPost.setHeader("Content-Type", "multipart/form-data");
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
return httpPost;
}
public static HttpPost uploadFileByInputStream(String url,File file, String fileKey,String fileName,
Map<String, String> params, Map<String, String> headers){
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody(fileKey,file, ContentType.MULTIPART_FORM_DATA,fileName);
for (Map.Entry<String,String> param : params.entrySet()){
StringBody stringBody = new StringBody(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());
}
httpPost.setHeader("Content-Type", "multipart/form-data");
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
return httpPost;
}
/**
*
* @param url 请求地址
* @param params 请求参数
* @param headers 请求头信息
* @param consumer 回调方法
* @throws IOException io异常
*/
public static void apiPost(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
callBackRequest(httpConnection, httpPost, consumer);
}
/**
*
* @param url 请求地址
* @param params 请求参数
* @param headers 请求头
* @param consumer 回调方法
* @throws IOException io异常
*/
public static void apiPut(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
callBackRequest(httpConnection, httpPut, consumer);
}
/**
* 回调请求方法
* @param httpClient httpclient对象
* @param request 请求对象
* @param consumer 回调方法
* @throws IOException io异常
*/
private static 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;
}
// new CloseThread(httpClient,response).run();
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
}
/**
* 请求封装
* @param httpClient httpclient对象
* @param request 请求对象
* @return 第三方请求结果
* @throws IOException io异常
*/
public static ResponeVo baseRequest(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException {
ResponeVo responeVo = new ResponeVo();
CloseableHttpResponse response = null;
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());
} catch (Exception e) {
toolUtil.writeErrorLog(" http调用失败:" + e);
throw e;
}
// new CloseThread(httpClient,response).run();
ExtendedIOUtils.closeQuietly(httpClient);
ExtendedIOUtils.closeQuietly(response);
return responeVo;
}
/**
* 异步get请求
*
* @param url 请求地址
* @return 请求结果 Future类
* @throws IOException io异常
*/
public static Future<ResponeVo> asyncApiGet(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> 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));
}
public static Future<ResponeVo> asyncApiUploadFile(String url,InputStream inputStream, String fileKey,String fileName,
Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = uploadFileByInputStream(url,inputStream, fileKey,fileName, paramsMap, headerMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
}
public static Future<ResponeVo> asyncApiUploadFile(String url,File file, String fileKey,String fileName,
Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = uploadFileByInputStream(url,file, fileKey,fileName, paramsMap, headerMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
}
public static Future<ResponeVo> asyncApiUploadFileById(String url,int id, String fileKey,String fileName,
Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
InputStream inputStream = ImageFileManager.getInputStreamById(id);
HttpPost httpPost = uploadFileByInputStream(url,inputStream, fileKey,fileName, paramsMap, headerMap);
return executorService.submit(new HttpAsyncThread(httpConnection, httpPost, DEFAULT_ENCODING));
}
/**
* 异步delete请求
*
* @param url 请求地址
* @return 请求结果Future类
* @throws IOException io异常
*/
public static Future<ResponeVo> asyncApiDelete(String url) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> 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 static Future<ResponeVo> asyncApiGet(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> 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 static Future<ResponeVo> asyncApiDelete(String url, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> 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 static Future<ResponeVo> asyncApiGet(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
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 static Future<ResponeVo> asyncApiDelete(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
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异常
*/
public static void asyncApiGet(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpGet httpGet = new HttpGet(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpGet, consumer));
}
/**
* 回调方法
*
* @param url 请求地址
* @param params 请求参数
* @param headers 请求头信息
* @param consumer 回调方法
* @throws IOException io异常
*/
public static void asyncApiDelete(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
Map<String, String> paramsMap = paramsHandle(params);
String getUrl = urlHandle(url, paramsMap);
Map<String, String> headerMap = headersHandle(headers);
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
HttpDelete httpDelete = new HttpDelete(getUrl.trim());
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpDelete, consumer));
}
public static Future<ResponeVo> asyncApiPost(String url, Map<String, String> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> 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 static Future<ResponeVo> asyncApiPut(String url, Map<String, String> params) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> 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 static Future<ResponeVo> asyncApiPost(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> 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 static Future<ResponeVo> asyncApiPut(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> 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异常
*/
public static void asyncApiPost(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPost httpPost = handleHttpPost(url, headerMap, paramsMap);
executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpPost, consumer));
}
/**
* @param url 请求地址
* @param params 请求参数
* @param headers 请求头信息
* @param consumer 回调方法
* @throws IOException io异常
*/
public static void asyncApiPut(String url, Map<String, String> params, Map<String, String> headers, Consumer<CloseableHttpResponse> consumer) throws IOException {
CloseableHttpClient httpConnection = HttpManager.getHttpConnection(url);
Map<String, String> paramsMap = paramsHandle(params);
Map<String, String> headerMap = headersHandle(headers);
HttpPut httpPut = handleHttpPut(url, headerMap, paramsMap);
executorService.execute(new HttpAsyncThreadCallBack(httpConnection, httpPut, consumer));
}
/**
* 处理post请求参数等根据请求头设置参数类型
* @param url 请求地址
* @param headerMap 请求头
* @param paramsMap 请求参数
* @return 请求结果
* @throws UnsupportedEncodingException 编码转换异常
*/
private static HttpPost handleHttpPost(String url, Map<String, String> headerMap, Map<String, String> paramsMap) throws UnsupportedEncodingException {
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();
}
}
if (Strings.isNullOrEmpty(contentType)) {
List<NameValuePair> nvps = new ArrayList<>();
for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), 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, String> entry : paramsMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
} else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) {
StringEntity stringEntity = new StringEntity(JSON.toJSONString(paramsMap));
httpPost.setEntity(stringEntity);
}
return httpPost;
}
private static HttpPut handleHttpPut(String url, Map<String, String> headerMap, Map<String, String> paramsMap) throws UnsupportedEncodingException {
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, String> entry : paramsMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), 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, String> entry : paramsMap.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPut.setEntity(new UrlEncodedFormEntity(nvps));
} else if (contentType.toUpperCase().startsWith(HttpArgsType.APPLICATION_JSON.toUpperCase())) {
StringEntity stringEntity = new StringEntity(JSON.toJSONString(paramsMap));
httpPut.setEntity(stringEntity);
}
return httpPut;
}
private static 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();
}
/**
* 请求头处理,添加全局请求头
* @param headers 请求头
* @return 处理后的请求头
*/
public static Map<String, String> headersHandle(Map<String, String> headers) {
Map<String, String> map = new HashMap<>();
if (headers != null && headers.size() > 0) {
if (GlobalStaticCache.header != null && GlobalStaticCache.header.size() > 0) {
map.putAll(GlobalStaticCache.header);
}
map.putAll(headers);
} else {
map.putAll(GlobalStaticCache.header);
}
return map;
}
/**
* 请求参数处理。添加全局请求参数
* @param params 请求参数
* @return 处理后的请求参数
*/
public static Map<String, String> paramsHandle(Map<String, String> params) {
Map<String, String> map = new HashMap<>();
if (params != null && params.size() > 0) {
if (GlobalStaticCache.paramMap != null && GlobalStaticCache.paramMap.size() > 0) {
map.putAll(GlobalStaticCache.paramMap);
}
map.putAll(params);
} else {
map.putAll(GlobalStaticCache.paramMap);
}
return map;
}
/**
* url地址处理get请求地址序列化
* @param url 请求地址
* @param params 请求参数
* @return 处理后的url
*/
public static String urlHandle(String url, Map<String, String> 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;
}
/**
* 请求参数序列化
* @param params 请求参数
* @return 处理后的参数
*/
private static String serializeParams(Map<String, String> params) {
if (params != null && params.size() > 0) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> 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;
}
}