diff --git a/src/main/java/com/zhgd/xmgl/util/HttpsUtils.java b/src/main/java/com/zhgd/xmgl/util/HttpsUtils.java new file mode 100644 index 0000000..3249718 --- /dev/null +++ b/src/main/java/com/zhgd/xmgl/util/HttpsUtils.java @@ -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 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 doPostSSL(String url,Map headers,String params,String paramsEncoding,Class 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); + } +}