验收修改

This commit is contained in:
pengjie 2024-05-21 12:39:04 +08:00
parent d91423afcd
commit 312a170edf

View File

@ -0,0 +1,173 @@
package com.zhgd.xmgl.util;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HttpsUtils {
private static final Logger logger= LoggerFactory.getLogger(HttpsUtils.class);
/**
* 连接超时设置
*/
private static final int TIMEOUT = 60 * 1000;
static HostnameVerifier hostnameVerifier = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
logger.warn("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
return true;
}
};
private static final class DefaultTrustManager implements 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 null;
}
}
public static String getExceptionDetail(Exception e) {
if (e == null) return "";
StringBuilder stringBuffer = new StringBuilder(e.toString() + "\n");
StackTraceElement[] messages = e.getStackTrace();
for (StackTraceElement message : messages) {
stringBuffer.append("\t").append(message.toString()).append("\n");
}
return stringBuffer.toString();
}
private static String getCharset(HttpsURLConnection connection){
String charset = "UTF-8";
Pattern pattern = Pattern.compile("charset=\\S*");
String contentTypeStr = connection.getContentType();
if (contentTypeStr == null || "".equals(contentTypeStr)) {
charset = "";
} else {
Matcher matcher = pattern.matcher(contentTypeStr);
if (matcher.find()) {
charset = matcher.group().replace("charset=", "");
}
if (charset == null || "".equals(charset)) {
charset = "";
}
}
return charset;
}
public static String doPost(String requestUrl, String jsonObj) throws Exception {
Map<String,String > headers = new HashMap<>();
headers.put("Content-type", "application/json; charset=utf-8");
headers.put("Accept", "application/json");
return doPostSSL(requestUrl, headers, jsonObj, "UTF-8", null);
}
/**
* POST: HTTPS协议json请求格式返回实例对象
*/
private static <T> T doPostSSL(String url,Map<String,String > headers,String params,String paramsEncoding,Class<T> targetClass){
String result="";
BufferedReader responseReader = null;
HttpsURLConnection httpsConn=null;
OutputStreamWriter paramsWriter = null;
int statusCode=500;
String msg="接口请求失败!";
try{
SSLContext ctx = null;
ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
URL realUrl = new URL(url);
httpsConn = (HttpsURLConnection) realUrl.openConnection();
httpsConn.setSSLSocketFactory(ctx.getSocketFactory());
httpsConn.setHostnameVerifier(hostnameVerifier);
httpsConn.setRequestMethod("POST");
httpsConn.setDoInput(true);
httpsConn.setDoOutput(true);
httpsConn.setConnectTimeout(TIMEOUT);
//请求头
if(null != headers && !headers.isEmpty()) headers.forEach(httpsConn::setRequestProperty);
httpsConn.connect();
paramsWriter= new OutputStreamWriter(httpsConn.getOutputStream(), paramsEncoding);
paramsWriter.write(params);
paramsWriter.flush();
// 定义 BufferedReader输入流来读取URL的响应
statusCode = httpsConn.getResponseCode();
InputStream input=null;
if (statusCode == HttpURLConnection.HTTP_OK
|| statusCode == HttpURLConnection.HTTP_CREATED
|| statusCode == HttpURLConnection.HTTP_ACCEPTED) {
input=httpsConn.getInputStream();
msg = "接口请求成功!";
} else {
input=httpsConn.getErrorStream();
msg = "接口请求失败状态码非200";
}
String charset = getCharset(httpsConn);
if (charset == null || "".equals(charset)) {
responseReader = new BufferedReader(new InputStreamReader(input));
} else {
responseReader = new BufferedReader(new InputStreamReader(input, charset));
}
String line;
while ((line = responseReader.readLine()) != null) {
result += line;
}
}catch(Exception e){
logger.error("doPostSSL 请求失败! URL={}, 异常为-->{}",url,getExceptionDetail(e));
}finally {
if(responseReader != null){
try {
responseReader.close();
} catch (IOException e) {
logger.error(getExceptionDetail(e));
}
}
if (httpsConn != null) {
try {
httpsConn.disconnect();
} catch (Exception e) {
logger.error(getExceptionDetail(e));
}
}
if (paramsWriter != null) {
try {
paramsWriter.close();
} catch (Exception e) {
logger.error(getExceptionDetail(e));
}
}
}
logger.info("doPostSSL URL={} 状态码{} {} headers={} params={} 请求结果:{}",url,statusCode,msg,headers,params,result);
if("".equals(result)){
logger.error("doPostSSL 请求失败 URL={}, headers={} 请求参数->{}",url,headers,params);
return null;
}
return JSONObject.parseObject(result,targetClass);
}
}