httputils 支持自定义requestConfig对象

dev
wangxuanran 2023-07-12 16:29:53 +08:00
parent 30a63c8c22
commit 79c4547d38
11 changed files with 104 additions and 110 deletions

View File

@ -20,6 +20,7 @@ import java.security.KeyManagementException;
import java.security.KeyStoreException; import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.util.Objects;
/** /**
@ -66,6 +67,13 @@ public class HttpManager {
* @return * @return
*/ */
public static CloseableHttpClient getHttpConnection(String url, CredentialsProvider credentialsProvider) { public static CloseableHttpClient getHttpConnection(String url, CredentialsProvider credentialsProvider) {
return getHttpConnection(url, credentialsProvider, null);
}
public static CloseableHttpClient getHttpConnection(String url, CredentialsProvider credentialsProvider, RequestConfig cusRequestConfigs) {
if(Objects.isNull(cusRequestConfigs)){
cusRequestConfigs = requestConfig;
}
if (url.trim().toUpperCase().startsWith(HttpArgsType.HTTP_HTTPS.toUpperCase())) { if (url.trim().toUpperCase().startsWith(HttpArgsType.HTTP_HTTPS.toUpperCase())) {
SSLContext sslContext; SSLContext sslContext;
SSLConnectionSocketFactory sslsf = null; SSLConnectionSocketFactory sslsf = null;
@ -84,66 +92,74 @@ public class HttpManager {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
HttpClientBuilder httpClientBuilder = HttpClients.custom() HttpClientBuilder httpClientBuilder = HttpClients.custom()
.setSSLSocketFactory(sslsf) .setSSLSocketFactory(sslsf)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setConnectionManager(manager) .setConnectionManager(manager)
.setConnectionManagerShared(true) .setConnectionManagerShared(true)
.setDefaultRequestConfig(requestConfig); .setDefaultRequestConfig(cusRequestConfigs);
if (credentialsProvider != null) { if (credentialsProvider != null) {
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
} }
return httpClientBuilder return httpClientBuilder
.build(); .build();
} else { } else {
HttpClientBuilder httpClientBuilder = HttpClients.custom() HttpClientBuilder httpClientBuilder = HttpClients.custom()
.setConnectionManager(manager) .setConnectionManager(manager)
.setDefaultRequestConfig(requestConfig) .setDefaultRequestConfig(cusRequestConfigs)
.setConnectionManagerShared(true); .setConnectionManagerShared(true);
if (credentialsProvider != null) { if (credentialsProvider != null) {
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
} }
return httpClientBuilder return httpClientBuilder
.build(); .build();
} }
} }
public static CloseableHttpClient getHttpConnection(String url, CredentialsProvider credentialsProvider, String sslPath, String password) { public static CloseableHttpClient getHttpConnection(String url, CredentialsProvider credentialsProvider, String sslPath, String password) {
return getHttpConnection(url, credentialsProvider, sslPath, password, null);
}
public static CloseableHttpClient getHttpConnection(String url, CredentialsProvider credentialsProvider, String sslPath,
String password, RequestConfig cusRequestConfigs) {
if(Objects.isNull(cusRequestConfigs)){
cusRequestConfigs = requestConfig;
}
if (url.trim().toUpperCase().startsWith(HttpArgsType.HTTP_HTTPS.toUpperCase())) { if (url.trim().toUpperCase().startsWith(HttpArgsType.HTTP_HTTPS.toUpperCase())) {
SSLContext sslContext; SSLContext sslContext;
SSLConnectionSocketFactory sslsf = null; SSLConnectionSocketFactory sslsf = null;
try { try {
sslContext = SSLContexts.custom() sslContext = SSLContexts.custom()
.loadTrustMaterial(new File(sslPath), password.toCharArray(), .loadTrustMaterial(new File(sslPath), password.toCharArray(),
new TrustSelfSignedStrategy()) new TrustSelfSignedStrategy())
.build(); .build();
sslsf = new SSLConnectionSocketFactory(sslContext, sslsf = new SSLConnectionSocketFactory(sslContext,
new String[]{"TLSv1"}, new String[]{"TLSv1"},
null, null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier()); SSLConnectionSocketFactory.getDefaultHostnameVerifier());
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | CertificateException | } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | CertificateException |
IOException e) { IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
HttpClientBuilder httpClientBuilder = HttpClients.custom() HttpClientBuilder httpClientBuilder = HttpClients.custom()
.setSSLSocketFactory(sslsf) .setSSLSocketFactory(sslsf)
.setConnectionManager(manager) .setConnectionManager(manager)
.setConnectionManagerShared(true) .setConnectionManagerShared(true)
.setDefaultRequestConfig(requestConfig); .setDefaultRequestConfig(cusRequestConfigs);
if (credentialsProvider != null) { if (credentialsProvider != null) {
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
} }
return httpClientBuilder return httpClientBuilder
.build(); .build();
} else { } else {
HttpClientBuilder httpClientBuilder = HttpClients.custom() HttpClientBuilder httpClientBuilder = HttpClients.custom()
.setConnectionManager(manager) .setConnectionManager(manager)
.setDefaultRequestConfig(requestConfig) .setDefaultRequestConfig(cusRequestConfigs)
.setConnectionManagerShared(true); .setConnectionManagerShared(true);
if (credentialsProvider != null) { if (credentialsProvider != null) {
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
} }
return httpClientBuilder return httpClientBuilder
.build(); .build();
} }
} }
} }

View File

@ -63,6 +63,8 @@ public class HttpUtils {
private String sslKeyPath = ""; private String sslKeyPath = "";
@Setter @Setter
private String password = ""; private String password = "";
@Setter
private RequestConfig requestConfig;
/** /**
@ -185,12 +187,12 @@ public class HttpUtils {
*/ */
private CloseableHttpClient getHttpClient(String url) { private CloseableHttpClient getHttpClient(String url) {
if (Strings.isNullOrEmpty(this.sslKeyPath)) { if (Strings.isNullOrEmpty(this.sslKeyPath)) {
return HttpManager.getHttpConnection(url, this.credentialsProvider); return HttpManager.getHttpConnection(url, this.credentialsProvider, requestConfig);
} else { } else {
return HttpManager.getHttpConnection(url, this.credentialsProvider, sslKeyPath, password); return HttpManager.getHttpConnection(url, this.credentialsProvider, sslKeyPath, password, requestConfig);
} }
} }
/** /**
* get * get
* *

View File

@ -76,6 +76,9 @@ public class ChildWorkFlowSplitAction extends SafeCusBaseAction {
if (!mapper.updateMainTable(billTable, hasMoreAccountField, null, requestId)) { if (!mapper.updateMainTable(billTable, hasMoreAccountField, null, requestId)) {
throw new CustomerException("更新主表是否包含多账套字段失败!"); throw new CustomerException("更新主表是否包含多账套字段失败!");
} }
if(!mapper.selectAccountNumber(id, billTable + "_dt" + insertDetailNo)){
throw new CustomerException("删除明细表数据失败!");
}
return; return;
} }
if (!mapper.updateMainTable(billTable, hasMoreAccountField, hasMoreAccountFieldValue, requestId)) { if (!mapper.updateMainTable(billTable, hasMoreAccountField, hasMoreAccountFieldValue, requestId)) {

View File

@ -1,38 +0,0 @@
package weaver.xuanran.wang.common.entity;
import aiyh.utils.httpUtil.ResponeVo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import weaver.xuanran.wang.common.service.CusDataDecipher;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* <h1></h1>
*
* @author xuanran.wang
* @date 2023/4/6 19:34
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class CusResponseSuccess {
private ResponeVo vo;
private Object requestParam;
private String successField;
private Object successValue;
private String errorMsg;
private String dataKey;
private Map<String, Object> response;
private CusDataDecipher cusDataDecipher;
private String url;
private Exception e;
private boolean checkResponse = true;
private Consumer<Exception> call;
}

View File

@ -10,6 +10,8 @@ import weaver.xuanran.wang.common.interfaces.CusAbstractTokenConf;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/** /**
* <h1>token </h1> * <h1>token </h1>
@ -21,6 +23,7 @@ public class TokenUtil {
private static final Map<String, CusAbstractTokenConf> TOKEN_MAP = new HashMap<>(8); private static final Map<String, CusAbstractTokenConf> TOKEN_MAP = new HashMap<>(8);
private static Util_Redis instance = null; private static Util_Redis instance = null;
private static boolean redis = false; private static boolean redis = false;
private static final Lock lock = new ReentrantLock();
{ {
try { try {
@ -41,25 +44,22 @@ public class TokenUtil {
if(Objects.isNull(conf)){ if(Objects.isNull(conf)){
throw new CustomerException("conf cant not be null!"); throw new CustomerException("conf cant not be null!");
} }
CusAbstractTokenConf token = TOKEN_MAP.get(key); lock.lock();
if(token == null){ try {
synchronized (TokenUtil.class){ CusAbstractTokenConf token = TOKEN_MAP.get(key);
token = TOKEN_MAP.get(key); if(token == null){
if(token == null){ return getTokenByHttp(key, conf);
return getTokenByHttp(key, conf);
}
} }
} long expiryTime = token.getExpiryTime();
long expiryTime = token.getExpiryTime(); if(System.currentTimeMillis() >= expiryTime){
if(System.currentTimeMillis() >= expiryTime){ return getTokenByHttp(key, conf);
synchronized (TokenUtil.class){
expiryTime = token.getExpiryTime();
if(System.currentTimeMillis() >= expiryTime){
return getTokenByHttp(key, conf);
}
} }
return token.getToken();
}catch (Exception e){
throw new CustomerException("get token error : current key is [ " + key + " ]",e);
}finally {
lock.unlock();
} }
return token.getToken();
} }
/** /**
@ -70,7 +70,7 @@ public class TokenUtil {
* @param obj token * @param obj token
* @return token * @return token
**/ **/
private static synchronized String getTokenByHttp(String key, CusAbstractTokenConf obj){ private static String getTokenByHttp(String key, CusAbstractTokenConf obj){
Map<String, Object> response = obj.tokenByHttp(); Map<String, Object> response = obj.tokenByHttp();
obj.buildTokenObj(response); obj.buildTokenObj(response);
TOKEN_MAP.put(key, obj); TOKEN_MAP.put(key, obj);

View File

@ -6,6 +6,7 @@ import aiyh.utils.httpUtil.ResponeVo;
import aiyh.utils.httpUtil.util.HttpUtils; import aiyh.utils.httpUtil.util.HttpUtils;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import weaver.xuanran.wang.sh_bigdata.common.entity.CusSuccess; import weaver.xuanran.wang.sh_bigdata.common.entity.CusSuccess;
@ -23,6 +24,23 @@ public class RequestMasterPlate{
private final HttpUtils httpUtils = new HttpUtils(); private final HttpUtils httpUtils = new HttpUtils();
private static final int HTTP_SUCCESS_CODE = 200; private static final int HTTP_SUCCESS_CODE = 200;
private static final int CONNECT_TIMEOUT = 1000 * 60 * 3;
private static final int CONNECTION_REQUEST_TIMEOUT = 1000 * 60 * 3;
private static final int SOCKET_TIMEOUT = 1000 * 60 * 3;
static RequestConfig requestConfig = RequestConfig.custom()
// 网络请求的超时时间
.setConnectTimeout(CONNECT_TIMEOUT)
// 连接池去获取连接的超时时间
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
// 设置socket超时时间
.setSocketTimeout(SOCKET_TIMEOUT)
.build();
{
httpUtils.setRequestConfig(requestConfig);
}
public <T> T apiGet(String url, Map<String, Object> params, Map<String, String> headers, CusSuccess cusSuccess){ public <T> T apiGet(String url, Map<String, Object> params, Map<String, String> headers, CusSuccess cusSuccess){
ResponeVo responeVo; ResponeVo responeVo;
try { try {

View File

@ -1,6 +1,7 @@
package weaver.xuanran.wang.sh_bigdata.common.util; package weaver.xuanran.wang.sh_bigdata.common.util;
import aiyh.utils.Util; import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.apache.dubbo.common.serialize.fastjson.FastJsonObjectOutput; import org.apache.dubbo.common.serialize.fastjson.FastJsonObjectOutput;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
@ -11,6 +12,8 @@ import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/** /**
* <h1>token </h1> * <h1>token </h1>
@ -38,25 +41,19 @@ public class TokenUtil {
* @param secret * @param secret
**/ **/
public static String getToken(String secret) { public static String getToken(String secret) {
CusToken token = TOKEN_MAP.get(secret); try {
if(token == null){ CusToken token = TOKEN_MAP.get(secret);
synchronized (TokenUtil.class){ if(token == null){
token = TOKEN_MAP.get(secret); return getTokenByHTTP(secret);
if(token == null){
return getTokenByHTTP(secret);
}
} }
} long expiryTime = token.getExpiryTime();
long expiryTime = token.getExpiryTime(); if(new Date().getTime() >= expiryTime){
if(new Date().getTime() >= expiryTime){ return getTokenByHTTP(secret);
synchronized (TokenUtil.class){
expiryTime = token.getExpiryTime();
if(new Date().getTime() >= expiryTime){
return getTokenByHTTP(secret);
}
} }
return token.getAccess_token();
}catch (Exception e){
throw new CustomerException("get token error : current secret is [ " + secret + " ]",e);
} }
return token.getAccess_token();
} }
/** /**

View File

@ -203,4 +203,8 @@ public class TestA extends BaseTest {
} }
return dataObject; return dataObject;
} }
@Test
public void testC(){
System.out.println(new Date().getTime());
}
} }

View File

@ -3,19 +3,11 @@ package xuanran.wang.http_test.test;
import aiyh.utils.httpUtil.ResponeVo; import aiyh.utils.httpUtil.ResponeVo;
import basetest.BaseTest; import basetest.BaseTest;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.cloudstore.api.util.Util_Redis;
import com.fapiao.neon.client.base.impl.RedisClientImpl;
import com.weaver.base.cache.redis.RedisCache;
import org.docx4j.wml.R;
import org.junit.Test; import org.junit.Test;
import weaver.session.util.RedisClient; import xuanran.wang.common.entity.CusResponseSuccess;
import weaver.session.util.RedisTemplate; import xuanran.wang.rest_test.CusRestTemplate;
import weaver.xuanran.wang.common.entity.CusResponseSuccess;
import xuanran.wang.http_test.rest_test.CusRestTemplate;
import xuanran.wang.http_test.rest_test.Stu;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
/** /**

View File

@ -1,4 +1,4 @@
package xuanran.wang.http_test.rest_test; package xuanran.wang.rest_test;
import aiyh.utils.Util; import aiyh.utils.Util;
import aiyh.utils.excention.CustomerException; import aiyh.utils.excention.CustomerException;
@ -13,7 +13,7 @@ import com.fasterxml.jackson.databind.type.TypeFactory;
import org.apache.commons.collections.MapUtils; import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import weaver.xuanran.wang.common.entity.CusResponseSuccess; import xuanran.wang.common.entity.CusResponseSuccess;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;

View File

@ -1,4 +1,4 @@
package xuanran.wang.http_test.rest_test; package xuanran.wang.rest_test;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data; import lombok.Data;