第三方服务替换成okhttp请求

master
anthonyywj2 3 years ago
parent 1286264e1c
commit c6203c598d

@ -74,11 +74,11 @@
<version>8.0.21</version>
<scope>runtime</scope>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.microsoft.sqlserver</groupId>-->
<!-- <artifactId>sqljdbc4</artifactId>-->
<!-- <version>4.0</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.microsoft.sqlserver</groupId>-->
<!-- <artifactId>sqljdbc4</artifactId>-->
<!-- <version>4.0</version>-->
<!-- </dependency>-->
<!--<dependency>-->
<!--<groupId>com.microsoft.sqlserver</groupId>-->
@ -167,7 +167,11 @@
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.10.0</version>
</dependency>
</dependencies>
<build>

@ -7,7 +7,8 @@ import com.glxp.mipsdl.admin.config.ThirdSysConfig;
import com.glxp.mipsdl.admin.dao.phxyy.BasicThirdSysDetailDao;
import com.glxp.mipsdl.admin.entity.phxyy.BasicThirdSysBusApiEntity;
import com.glxp.mipsdl.admin.entity.phxyy.BasicThirdSysDetailEntity;
import com.glxp.mipsdl.admin.req.*;
import com.glxp.mipsdl.admin.req.UdiwmsOnhandRequest;
import com.glxp.mipsdl.admin.req.UdiwmsOrderRequest;
import com.glxp.mipsdl.admin.req.phxyy.*;
import com.glxp.mipsdl.admin.res.phxyy.BussinessOriginTypeResponse;
import com.glxp.mipsdl.admin.service.phxyy.BasicThirdSysBusApiService;
@ -19,6 +20,8 @@ import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
*
@ -28,7 +31,8 @@ public class PhxyyClient {
@Resource
private ThirdSysConfig thirdSysConfig;
@Resource
private HttpClient httpClient;
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
@ -38,6 +42,22 @@ public class PhxyyClient {
return headers;
}
String[] getHeaderArray() {
List<String> headArray = new ArrayList<>();
headArray.add("Content-Type");
headArray.add("application/json");
if (StrUtil.isNotEmpty(thirdSysConfig.getThirdSysConfig().getApikey())) {
headArray.add("api_key");
headArray.add(thirdSysConfig.getThirdSysConfig().getApikey());
}
if (StrUtil.isNotEmpty(thirdSysConfig.getThirdSysConfig().getSecretkey())) {
headArray.add("secret_key");
headArray.add(thirdSysConfig.getThirdSysConfig().getSecretkey());
}
return (String[]) headArray.toArray();
}
@Resource
private BasicThirdSysBusApiService basicThirdSysBusApiService;
@Resource
@ -61,7 +81,7 @@ public class PhxyyClient {
public BaseResponse getUnit(PhUnitRequest unitRequest) {
BasicThirdSysDetailEntity basicThirdSysDetailEntity = basicThirdSysDetailDao.selectByKey("corpUrl", thirdSysConfig.getThirdSysConfig().getThirdId());
String response = HttpClient.postJson(thirdSysConfig.getThirdSysConfig().getThirdSysUrl() + basicThirdSysDetailEntity.getValue(), unitRequest, getHeaders());
String response = httpClient.postJson(thirdSysConfig.getThirdSysConfig().getThirdSysUrl() + basicThirdSysDetailEntity.getValue(), unitRequest, getHeaderArray());
BaseResponse baseResponse =
JSONObject.parseObject(response, new TypeReference<BaseResponse>() {
});
@ -70,7 +90,7 @@ public class PhxyyClient {
public BaseResponse getProducts(PhProductRequest udiwmsProductRequest) {
BasicThirdSysDetailEntity basicThirdSysDetailEntity = basicThirdSysDetailDao.selectByKey("piQueryUrl", thirdSysConfig.getThirdSysConfig().getThirdId());
String response = HttpClient.postJson(thirdSysConfig.getThirdSysConfig().getThirdSysUrl() + basicThirdSysDetailEntity.getValue(), udiwmsProductRequest, getHeaders());
String response = httpClient.postJson(thirdSysConfig.getThirdSysConfig().getThirdSysUrl() + basicThirdSysDetailEntity.getValue(), udiwmsProductRequest, getHeaderArray());
BaseResponse baseResponse =
JSONObject.parseObject(response, new TypeReference<BaseResponse>() {
});
@ -79,7 +99,7 @@ public class PhxyyClient {
public BaseResponse getOrderTypes(PhBusTypeRequest udiwmsBusTypeRequest) {
BasicThirdSysDetailEntity basicThirdSysDetailEntity = basicThirdSysDetailDao.selectByKey("busTypeQueryUrl", thirdSysConfig.getThirdSysConfig().getThirdId());
String response = HttpClient.postJson(thirdSysConfig.getThirdSysConfig().getThirdSysUrl() + basicThirdSysDetailEntity.getValue(), udiwmsBusTypeRequest, getHeaders());
String response = httpClient.postJson(thirdSysConfig.getThirdSysConfig().getThirdSysUrl() + basicThirdSysDetailEntity.getValue(), udiwmsBusTypeRequest, getHeaderArray());
BaseResponse baseResponse =
JSONObject.parseObject(response, new TypeReference<BaseResponse>() {
});
@ -96,7 +116,7 @@ public class PhxyyClient {
BussinessOriginTypeResponse bussinessOriginTypeResponse = bussinessOriginTypeService.findByKey(udiwmsOrderRequest.getBillType(), thirdSysConfig.getThirdSysConfig().getThirdId());
udiwmsOrderRequest.setBillType(bussinessOriginTypeResponse.getThirdAction());
BasicThirdSysBusApiEntity basicThirdSysBusApiEntity = basicThirdSysBusApiService.selectByKey(bussinessOriginTypeResponse.getThirdAction(), bussinessOriginTypeResponse.getThirdSys(), 1);
String response = HttpClient.postJson(thirdSysConfig.getThirdSysConfig().getThirdSysUrl() + basicThirdSysBusApiEntity.getUrl(), udiwmsOrderRequest, getHeaders());
String response = httpClient.postJson(thirdSysConfig.getThirdSysConfig().getThirdSysUrl() + basicThirdSysBusApiEntity.getUrl(), udiwmsOrderRequest, getHeaderArray());
BaseResponse baseResponse =
JSONObject.parseObject(response, new TypeReference<BaseResponse>() {
});
@ -108,7 +128,7 @@ public class PhxyyClient {
return ResultVOUtils.error(500, "单据类型不能未空");
}
BasicThirdSysDetailEntity basicThirdSysDetailEntity = basicThirdSysDetailDao.selectByKey("orderSubmitUrl", thirdSysConfig.getThirdSysConfig().getThirdId());
String response = HttpClient.postJson(thirdSysConfig.getThirdSysConfig().getThirdSysUrl() + basicThirdSysDetailEntity.getValue(), udiwmsOrderRequest, getHeaders());
String response = httpClient.postJson(thirdSysConfig.getThirdSysConfig().getThirdSysUrl() + basicThirdSysDetailEntity.getValue(), udiwmsOrderRequest, getHeaderArray());
BaseResponse baseResponse =
JSONObject.parseObject(response, new TypeReference<BaseResponse>() {
});
@ -117,7 +137,7 @@ public class PhxyyClient {
public BaseResponse getInvProducts(UdiwmsOnhandRequest udiwmsOnhandRequest) {
BasicThirdSysDetailEntity basicThirdSysDetailEntity = basicThirdSysDetailDao.selectByKey("invPiUrl", thirdSysConfig.getThirdSysConfig().getThirdId());
String response = HttpClient.postJson(thirdSysConfig.getThirdSysConfig().getThirdSysUrl() + basicThirdSysDetailEntity.getValue(), udiwmsOnhandRequest, getHeaders());
String response = httpClient.postJson(thirdSysConfig.getThirdSysConfig().getThirdSysUrl() + basicThirdSysDetailEntity.getValue(), udiwmsOnhandRequest, getHeaderArray());
BaseResponse baseResponse =
JSONObject.parseObject(response, new TypeReference<BaseResponse>() {
});
@ -126,7 +146,7 @@ public class PhxyyClient {
public BaseResponse getWarehouse(PhWarehouseRequest udiwmsWarehouseRequest) {
BasicThirdSysDetailEntity basicThirdSysDetailEntity = basicThirdSysDetailDao.selectByKey("warehouseQueryUrl", thirdSysConfig.getThirdSysConfig().getThirdId());
String response = HttpClient.postJson(thirdSysConfig.getThirdSysConfig().getThirdSysUrl() + basicThirdSysDetailEntity.getValue(), udiwmsWarehouseRequest, getHeaders());
String response = httpClient.postJson(thirdSysConfig.getThirdSysConfig().getThirdSysUrl() + basicThirdSysDetailEntity.getValue(), udiwmsWarehouseRequest, getHeaderArray());
BaseResponse baseResponse =
JSONObject.parseObject(response, new TypeReference<BaseResponse>() {
});

@ -0,0 +1,97 @@
package com.glxp.mipsdl.admin.config;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
/**
* @author Answer.AI.L
* @date 2019-04-09
*/
@Configuration
public class OkHttpConfiguration {
@Value("${ok.http.connect-timeout}")
private Integer connectTimeout;
@Value("${ok.http.read-timeout}")
private Integer readTimeout;
@Value("${ok.http.write-timeout}")
private Integer writeTimeout;
@Value("${ok.http.max-idle-connections}")
private Integer maxIdleConnections;
@Value("${ok.http.keep-alive-duration}")
private Long keepAliveDuration;
@Bean
public OkHttpClient okHttpClient() {
return new OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory(), x509TrustManager())
// 是否开启缓存
.retryOnConnectionFailure(false)
.connectionPool(pool())
.connectTimeout(connectTimeout, TimeUnit.SECONDS)
.readTimeout(readTimeout, TimeUnit.SECONDS)
.writeTimeout(writeTimeout, TimeUnit.SECONDS)
.hostnameVerifier((hostname, session) -> true)
// 设置代理
// .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888)))
// 拦截器
// .addInterceptor()
.build();
}
@Bean
public X509TrustManager x509TrustManager() {
return new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
}
@Bean
public SSLSocketFactory sslSocketFactory() {
try {
// 信任任何链接
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
return null;
}
@Bean
public ConnectionPool pool() {
return new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.SECONDS);
}
}

@ -0,0 +1,182 @@
package com.glxp.mipsdl.admin.http;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Map;
/**
* @author Answer.AI.L
* @date 2019-04-09
*/
@Slf4j
@Component
public class OkHttpCli {
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final MediaType XML = MediaType.parse("application/xml; charset=utf-8");
@Resource
private OkHttpClient okHttpClient;
/**
* get
*
* @param url url
* @return string
*/
public String doGet(String url) {
return doGet(url, null, null);
}
/**
* get
*
* @param url url
* @param params map
* @return string
*/
public String doGet(String url, Map<String, String> params) {
return doGet(url, params, null);
}
/**
* get
*
* @param url url
* @param headers {k1, v1 k2, v2, ...}
* @return string
*/
public String doGet(String url, String[] headers) {
return doGet(url, null, headers);
}
/**
* get
*
* @param url url
* @param params map
* @param headers {k1, v1 k2, v2, ...}
* @return string
*/
public String doGet(String url, Map<String, String> params, String[] headers) {
StringBuilder sb = new StringBuilder(url);
if (params != null && params.keySet().size() > 0) {
boolean firstFlag = true;
for (String key : params.keySet()) {
if (firstFlag) {
sb.append("?").append(key).append("=").append(params.get(key));
firstFlag = false;
} else {
sb.append("&").append(key).append("=").append(params.get(key));
}
}
}
Request.Builder builder = new Request.Builder();
if (headers != null && headers.length > 0) {
if (headers.length % 2 == 0) {
for (int i = 0; i < headers.length; i = i + 2) {
builder.addHeader(headers[i], headers[i + 1]);
}
} else {
log.warn("headers's length[{}] is error.", headers.length);
}
}
Request request = builder.url(sb.toString()).build();
log.info("do get request and url[{}]", sb.toString());
return execute(request);
}
/**
* post
*
* @param url url
* @param params map
* @return string
*/
public String doPost(String url, Map<String, String> params) {
FormBody.Builder builder = new FormBody.Builder();
if (params != null && params.keySet().size() > 0) {
for (String key : params.keySet()) {
builder.add(key, params.get(key));
}
}
Request request = new Request.Builder().url(url).post(builder.build()).build();
log.info("do post request and url[{}]", url);
return execute(request);
}
/**
* post , json
*
* @param url url
* @param json , json
* @return string
*/
public String doPostJson(String url, String json) {
log.info("do post request and url[{}]", url);
return exectePost(url, json, JSON);
}
public String doPostJson(String url, String json, String... headers) {
log.info("do post request and url[{}]", url);
return exectePost(url, json, JSON, headers);
}
/**
* post , xml
*
* @param url url
* @param xml , xml
* @return string
*/
public String doPostXml(String url, String xml) {
log.info("do post request and url[{}]", url);
return exectePost(url, xml, XML);
}
private String exectePost(String url, String data, MediaType contentType) {
RequestBody requestBody = RequestBody.create(contentType, data);
Request request = new Request.Builder().url(url).post(requestBody).build();
return execute(request);
}
private String exectePost(String url, String data, MediaType contentType, String... headParms) {
RequestBody requestBody = RequestBody.create(contentType, data);
Request request = new Request.Builder().headers(Headers.of(headParms)).url(url).post(requestBody).build();
return execute(request);
}
private String execute(Request request) {
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
log.error(ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return "";
}
}

@ -1,5 +1,6 @@
package com.glxp.mipsdl.admin.http;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.glxp.mipsdl.admin.req.system.PostFileThrOrderRequest;
@ -12,6 +13,10 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service
public class UdiwmsClient {
@ -23,7 +28,8 @@ public class UdiwmsClient {
private String apiKey;
@Value("${API_SECRET}")
private String apiSecret;
@Resource
HttpClient httpClient;
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
@ -33,9 +39,23 @@ public class UdiwmsClient {
return headers;
}
String[] getHeaderArray() {
List<String> headArray = new ArrayList<>();
headArray.add("Content-Type");
headArray.add("application/json");
if (StrUtil.isNotEmpty(apiKey)) {
headArray.add("api_key");
headArray.add(apiKey);
}
if (StrUtil.isNotEmpty(apiSecret)) {
headArray.add("secret_key");
headArray.add("apiSecret");
}
return (String[]) headArray.toArray();
}
public BaseResponse postProducts(PostThrProductsRequest postThrProductsRequest) {
String response = HttpClient.postJson(udiWmsUrl + "/udiwms/thrsys/postThrProducts", postThrProductsRequest, getHeaders());
String response = httpClient.postJson(udiWmsUrl + "/udiwms/thrsys/postThrProducts", postThrProductsRequest, getHeaderArray());
BaseResponse baseResponse =
JSONObject.parseObject(response, new TypeReference<BaseResponse>() {
});
@ -44,7 +64,7 @@ public class UdiwmsClient {
public BaseResponse postCorps(PostThrCorpRequest postThrCorpRequest) {
postThrCorpRequest.setUploadType("文件导入");
String response = HttpClient.postJson(udiWmsUrl + "/udiwms/thrsys/postCorps", postThrCorpRequest, getHeaders());
String response = httpClient.postJson(udiWmsUrl + "/udiwms/thrsys/postCorps", postThrCorpRequest, getHeaderArray());
BaseResponse baseResponse =
JSONObject.parseObject(response, new TypeReference<BaseResponse>() {
});
@ -52,7 +72,7 @@ public class UdiwmsClient {
}
public BaseResponse postOrderDetail(PostFileThrOrderRequest postFileThrOrderRequest) {
String response = HttpClient.postJson(udiWmsUrl + "/udiwms/thrsys/postFileOrder", postFileThrOrderRequest, getHeaders());
String response = httpClient.postJson(udiWmsUrl + "/udiwms/thrsys/postFileOrder", postFileThrOrderRequest, getHeaderArray());
BaseResponse baseResponse =
JSONObject.parseObject(response, new TypeReference<BaseResponse>() {
});
@ -60,7 +80,7 @@ public class UdiwmsClient {
}
public BaseResponse postInvProducts(PostThrInvProductsRequest postThrInvProductsRequest) {
String response = HttpClient.postJson(udiWmsUrl + "/udiwms/thrsys/postInvProducts", postThrInvProductsRequest, getHeaders());
String response = httpClient.postJson(udiWmsUrl + "/udiwms/thrsys/postInvProducts", postThrInvProductsRequest, getHeaderArray());
BaseResponse baseResponse =
JSONObject.parseObject(response, new TypeReference<BaseResponse>() {
});

@ -1,19 +1,28 @@
package com.glxp.mipsdl.admin.util;
import com.alibaba.fastjson.JSONObject;
import com.glxp.mipsdl.admin.http.OkHttpCli;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@Service
public class HttpClient {
private static final Logger logger = LoggerFactory.getLogger(HttpClient.class);
public static String post(String url, Object object) {
@Resource
OkHttpCli okHttpCli;
private final Logger logger = LoggerFactory.getLogger(HttpClient.class);
public String post(String url, Object object) {
RestTemplate restTemplate = new RestTemplate();
String json = JSONObject.toJSON(object).toString();
MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
@ -27,7 +36,7 @@ public class HttpClient {
return response;
}
public static String postJson(String url, Object object) {
public String postJson(String url, Object object) {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(600000);
factory.setReadTimeout(600000);
@ -42,7 +51,7 @@ public class HttpClient {
}
public static String postJson(String url, Object object, HttpHeaders headers) {
public String postJson(String url, Object object, HttpHeaders headers) {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(600000);
factory.setReadTimeout(600000);
@ -55,4 +64,13 @@ public class HttpClient {
return response;
}
public String postJson(String url, Object object, String... headers) {
String json = JSONObject.toJSON(object).toString();
logger.info(url + "\n" + json);
String response = okHttpCli.doPostJson(url, json, headers);
logger.info(response);
return response;
}
}

@ -4,7 +4,7 @@ spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#spring.datasource.jdbc-url=jdbc:mysql://192.168.235.137:33306/udiwms_erp?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.jdbc-url=jdbc:mysql://127.0.0.1:3306/udiwms?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=Glxp@6066
spring.datasource.password=123456
#spring.datasource.password=89083fb2fc145533
logging.level.com.glxp.mipsdl.admin.dao=debug
#logging.level.com.glxp.mipsdl.admin.barcode=debug
@ -22,7 +22,8 @@ spring.servlet.multipart.max-request-size=200MB
server.connectionTimeout=180000
#U8参数
#udi管理系统IP地址上传文件解析后回传
UDIWMS_IP=http://192.168.0.109:9150/UDI_WMS_MC
UDIWMS_IP=http://127.0.0.1:9991
#UDIWMS_IP=http://139.9.178.73:8080/UDI_WMS_MC
API_KEY=1102
API_SECRET=4dc07484afd34e8083ba96e8fe564224
#文件导入
@ -31,5 +32,12 @@ FILE_VERSION_FLAG=PHXYY
#接口实时获取
#0.NULL(空,未配置),1.YONGYOU_U8_V3.1(用友3.1版本,片仔癀诊断) 2.YG_UDPLAT_V1.0(阳光采购平台) 3.TEST(标准接口,测试用),4.PHXYY(诏安县医院)
ONLINE_VESRION_FLAG=PHXYY
THIRD_ID=thirdId
ok.http.connect-timeout=3000
ok.http.read-timeout=3000
ok.http.write-timeout=3000
# 连接池中整体的空闲连接的最大数量
ok.http.max-idle-connections=200
# 连接空闲时间最多为 300 秒
ok.http.keep-alive-duration=300

@ -1,7 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<contextName>logback</contextName>
<property name="log.path" value="D:\\udiwms\\logs\\UDIC_UCLOUD_SERVER\\" />
<!-- /home/glxpdata/udiwms/UDIC_UCLOUD_SERVER/-->
<!-- D:\\udiwms\\logs\\UDIC_UCLOUD_SERVER\\-->
<property name="log.path" value="/home/glxpdata/udiwms/UDIC_UCLOUD_SERVER/" />
<!--输出到控制台-->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<!-- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">

Loading…
Cancel
Save