Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
matrix.boot.common.utils.http.HttpClientUtil Maven / Gradle / Ivy
package matrix.boot.common.utils.http;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import matrix.boot.common.enums.HttpParamTypeEnum;
import matrix.boot.common.exception.ServiceException;
import matrix.boot.common.utils.BIOStreamUtil;
import matrix.boot.common.utils.StringUtil;
import matrix.boot.common.dto.HttpCertDto;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
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.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Map;
/**
* http请求工具
*
* @author wangcheng
*/
@Slf4j
public class HttpClientUtil {
/**
* get请求
*
* @param url 连接地址
* @param callBack 回调方法
* @return T
*/
public static T sendGet(String url, CallBack callBack) {
return sendGet(url, null, null, null, callBack);
}
/**
* get请求
*
* @param url 连接地址
* @param params 参数
* @param callBack 回调方法
* @return T
*/
public static T sendGet(String url, Map params, CallBack callBack) {
return sendGet(url, null, params, null, callBack);
}
/**
* get请求
*
* @param url 连接地址
* @param headers 请求头
* @param params 参数
* @param callBack 回调方法
* @return T
*/
public static T sendGet(String url, Map headers, Map params, CallBack callBack) {
return sendGet(url, headers, params, null, callBack);
}
/**
* get请求
*
* @param url 连接地址
* @param certDto 证书(https需要)
* @param callBack 回调方法
* @return T
*/
public static T sendGet(String url, HttpCertDto certDto, CallBack callBack) {
return sendGet(url, null, null, certDto, callBack);
}
/**
* post请求
*
* @param url 连接地址
* @param body 参数
* @param paramType 参数类型
* @param callBack 回调方法
* @return T
*/
public static T sendPost(String url, String body, HttpParamTypeEnum paramType, CallBack callBack) {
return sendPost(url, null, body, paramType, null, callBack);
}
/**
* post请求
*
* @param url 连接地址
* @param headers 请求头
* @param body 参数
* @param paramType 参数类型
* @param callBack 回调方法
* @return T
*/
public static T sendPost(String url, Map headers, String body, HttpParamTypeEnum paramType, CallBack callBack) {
return sendPost(url, headers, body, paramType, null, callBack);
}
/**
* post请求
*
* @param url 连接地址
* @param headers 请求头
* @param params 参数
* @param paramType 参数类型
* @param callBack 回调方法
* @return T
*/
public static T sendPost(String url, Map headers, Map params, HttpParamTypeEnum paramType, CallBack callBack) {
return sendPost(url, headers, params, paramType, null, callBack);
}
/**
* post请求
*
* @param url 连接地址
* @param headers 请求头
* @param params 参数
* @param paramType 参数类型
* @param certDto 证书(https需要)
* @param callBack 回调方法
* @return T
*/
public static T sendPost(String url, Map headers, Map params, HttpParamTypeEnum paramType, HttpCertDto certDto, CallBack callBack) {
if (HttpParamTypeEnum.JSON.name().equals(paramType.name())) {
return sendPost(url, headers, JSONObject.toJSONString(params), paramType, certDto, callBack);
} else if (HttpParamTypeEnum.XML.name().equals(paramType.name())) {
throw new ServiceException("please invoke sendPost(String url, String body, HttpParamEnum paramType, CallBack callBack)");
} else if (HttpParamTypeEnum.FORM.name().equals(paramType.name())) {
return sendPost(url, headers, toParams(params, null), paramType, certDto, callBack);
}
throw new ServiceException("not support paramType");
}
/**
* 基础get方法
*
* @param url 连接地址
* @param headers 请求头
* @param params 参数
* @param certDto 证书(https需要)
* @param callBack 回调方法
* @return T
*/
public static T sendGet(String url, Map headers, Map params, HttpCertDto certDto, CallBack callBack) {
HttpGet httpGet = new HttpGet(toParams(params, url));
return invoke(httpGet, headers, certDto, callBack);
}
/**
* 基础post方法
*
* @param url 连接地址
* @param headers 请求头
* @param body 参数
* @param paramType 参数类型
* @param certDto 证书(https需要)
* @param callBack 回调方法
* @return T
*/
public static T sendPost(String url, Map headers, String body, HttpParamTypeEnum paramType, HttpCertDto certDto, CallBack callBack) {
try {
HttpPost httpPost = new HttpPost(url);
if (!StringUtil.isEmpty(body)) {
if (HttpParamTypeEnum.JSON.name().equals(paramType.name())) {
httpPost.addHeader("Content-type", "application/json; charset=UTF-8");
} else if (HttpParamTypeEnum.XML.name().equals(paramType.name())) {
httpPost.addHeader("Content-type", "application/xml; charset=UTF-8");
}
httpPost.setEntity(new StringEntity(body, StandardCharsets.UTF_8));
}
return invoke(httpPost, headers, certDto, callBack);
} catch (Exception e) {
throw new ServiceException(e);
}
}
/**
* 调用
*
* @param request 请求体
* @param headers http头
* @param certDto 证书
* @param callBack 调用函数
* @return T
*/
private static T invoke(final HttpRequestBase request, final Map headers, final HttpCertDto certDto, final CallBack callBack) {
CloseableHttpClient client = null;
try {
if (request.getConfig() == null) {
request.setConfig(RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(10000).build());
}
//加入请求头
if (headers != null && !headers.isEmpty()) {
headers.forEach(request::addHeader);
}
if (certDto != null) {
client = HttpClients.custom().setConnectionManager(getCertConnectionManager(certDto)).build();
} else {
client = HttpClients.createDefault();
}
CloseableHttpResponse response = client.execute(request);
if (callBack != null) {
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
return callBack.execute(response.getEntity());
} else {
return callBack.failExecute(response.getEntity());
}
}
log.warn("HttpClientUtil no callback function");
return null;
} catch (Exception e) {
throw new ServiceException(e);
} finally {
BIOStreamUtil.closeStream(client);
}
}
/**
* get请求参数拼接
* map -> a=1&b=1
*
* @param params 参数体
* @param url 连接
* @return 拼接后的连接
*/
private static String toParams(Map params, String url) {
if (params == null || params.isEmpty()) {
return url;
}
StringBuilder result = new StringBuilder();
for (String key : params.keySet()) {
if (result.length() > 0) {
result.append("&");
}
String value = String.valueOf(params.get(key));
result.append(StringUtil.encodeUrl(key));
if (value != null && !value.isEmpty()) {
result.append("=");
result.append(StringUtil.encodeUrl(value));
}
}
if (url == null) {
return result.toString();
}
if (url.indexOf("?") <= 0) {
return url + "?" + result;
} else {
return url + "&" + result;
}
}
/**
* 获取证书连接管理器
*
* @param certDto 证书参数
* @return 基础client管理器
*/
private static BasicHttpClientConnectionManager getCertConnectionManager(HttpCertDto certDto) {
try {
// 证书
char[] password = certDto.getPassword().toCharArray();
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(certDto.getCertStream(), password);
// 实例化密钥库 & 初始化密钥工厂
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, password);
// 创建 SSLContext
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1"}, null, new DefaultHostnameVerifier());
return new BasicHttpClientConnectionManager(RegistryBuilder.create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslConnectionSocketFactory).build(), null, null, null);
} catch (Exception e) {
throw new ServiceException(e);
}
}
/**
* 回调函数
*/
@FunctionalInterface
public interface CallBack {
/**
* 返回200执行处理
*
* @param entity http实体
* @return 用户处理结果
*/
T execute(HttpEntity entity);
/**
* 返回非200执行处理
*
* @param entity http实体
* @return 用户处理结果
*/
default T failExecute(HttpEntity entity) {
try {
log.error(EntityUtils.toString(entity));
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
}
}