package com.ydtech.utils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.ydtech.modules.nai.httpvo.HeadMessage; import com.ydtech.utils.RSA.RSAUtils; import org.apache.commons.text.StringEscapeUtils; 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.HttpPost; import org.apache.http.conn.socket.LayeredConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.conn.ssl.X509HostnameVerifier; 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.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.util.EntityUtils; import javax.net.ssl.*; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.security.GeneralSecurityException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @ClassName HttpsPostUtil * @Description: TODO * @Author * @Date 2021/5/24 **/ public class HttpsPostUtil { private static RequestConfig requestConfig; private static PoolingHttpClientConnectionManager connMgr; private static final int MAX_TIMEOUT = 7000; static { // 设置连接池 connMgr = new PoolingHttpClientConnectionManager(); // 设置连接池大小 connMgr.setMaxTotal(100); connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal()); RequestConfig.Builder configBuilder = RequestConfig.custom(); // 设置连接超时 configBuilder.setConnectTimeout(MAX_TIMEOUT); // 设置读取超时 configBuilder.setSocketTimeout(MAX_TIMEOUT); // 设置从连接池获取连接实例的超时 configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT); // 在提交请求之前 测试连接是否可用 configBuilder.setStaleConnectionCheckEnabled(true); requestConfig = configBuilder.build(); } //添加主机名验证程序类,设置不验证主机 private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; //添加信任主机 private static void trustAllHosts() { // 创建不验证证书链的信任管理器 这里使用的是x509证书 TrustManager[] trustAllCerts = new TrustManager[]{new MyX509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { } }}; // 安装所有信任的信任管理器 try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); //HttpsURLConnection通过SSLSocket来建立与HTTPS的安全连接,SSLSocket对象是由SSLSocketFactory生成的。 HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } } public static String sendPost(String urls, String param) { @SuppressWarnings("unused") JSONObject jsonObject = null; StringBuffer sb = new StringBuffer(); try { //建立连接 URL url = new URL(urls); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); // connection.setRequestMethod(RequestMethod); //设置请求内容编码格式 connection.setRequestProperty("content-type", "application/json;charset=UTF-8"); connection.setRequestProperty("Accept", "application/json;charset=UTF-8"); connection.setConnectTimeout(60000); connection.setReadTimeout(60000); if (param != null) { OutputStream out = connection.getOutputStream(); out.write(param.getBytes("UTF-8")); out.close(); } //流处理 InputStream in1 = connection.getInputStream(); // InputStreamReader inputReader = new InputStreamReader(input,"UTF-8"); BufferedReader reader = new BufferedReader(new InputStreamReader(in1, "GBK")); // 请求返回的状态 if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) { // 请求返回的数据 in1 = connection.getInputStream(); String lines; reader = new BufferedReader(new InputStreamReader(in1, "GBK")); while ((lines = reader.readLine()) != null) { sb.append(lines).append("\n"); } return sb.toString(); } else { } //关闭连接、释放资源 reader.close(); in1.close(); connection.disconnect(); } catch (Exception e) { } return null; } public static String sendCBITPost_self(String urls, String param) { @SuppressWarnings("unused") JSONObject jsonObject = null; StringBuffer sb = new StringBuffer(); try { //建立连接 URL url = new URL(urls); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); // connection.setRequestMethod(RequestMethod); //设置请求内容编码格式 connection.setRequestProperty("content-type", "application/json;charset=UTF-8"); connection.setRequestProperty("Accept", "application/json;charset=UTF-8"); connection.setConnectTimeout(60000); connection.setReadTimeout(60000); if (param != null) { OutputStream out = connection.getOutputStream(); out.write(param.getBytes("UTF-8")); out.close(); } //流处理 InputStream in1 = connection.getInputStream(); // InputStreamReader inputReader = new InputStreamReader(input,"UTF-8"); BufferedReader reader = null; // 请求返回的状态 if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) { // 请求返回的数据 in1 = connection.getInputStream(); String lines; reader = new BufferedReader(new InputStreamReader(in1, "UTF-8")); while ((lines = reader.readLine()) != null) { sb.append(lines).append("\n"); } return sb.toString(); } else { } //关闭连接、释放资源 reader.close(); in1.close(); connection.disconnect(); } catch (Exception e) { } return null; } public static String sendCBITPost(String urls, String param, String ZJPT_PUBLIC_KEY, String HZHB_PRIVATE_KEY) { @SuppressWarnings("unused") JSONObject jsonObject = null; StringBuffer sb = new StringBuffer(); try { //加密加签 //调用工具类加密加签,获取密文和签名 Map encry = RSAUtils.encryptAndSign(param, ZJPT_PUBLIC_KEY, HZHB_PRIVATE_KEY, "UTF-8", true, true); String req_content = encry.get("CONTENT");//密文 System.out.println("加密后的请求参数req_content=" + req_content); String req_sign = encry.get("SIGNATURE");//签名,放在请求头中 System.out.println("最终请求头中的签名req_sign=" + req_sign); Map reqMap = new HashMap<>(); reqMap.put("bizContent", req_content);//bizContent作为key,密文作为value,转json String reqContent = JSON.toJSONString(reqMap);//请求入参,放在请求体中 System.out.println("最终请求体中的请求参数reqContent=" + reqContent); //建立连接 URL url = new URL(urls); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); // connection.setRequestMethod(RequestMethod); //设置请求内容编码格式 connection.setRequestProperty("content-type", "application/json;charset=utf-8"); connection.setRequestProperty("Accept", "application/json;charset=utf-8"); connection.setRequestProperty("Signature", req_sign); connection.setRequestProperty("PartnerCode", "p_taiyuantianqin"); connection.setConnectTimeout(60000); connection.setReadTimeout(60000); if (reqContent != null) { OutputStream out = connection.getOutputStream(); out.write(reqContent.getBytes("UTF-8")); out.close(); } //流处理 InputStream in1 = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in1, "GBK")); // 请求返回的状态 if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) { // 请求返回的数据 in1 = connection.getInputStream(); String lines; reader = new BufferedReader(new InputStreamReader(in1, "GBK")); while ((lines = reader.readLine()) != null) { sb.append(lines).append("\n"); } String resp_sign = connection.getHeaderField("Signature"); //验签解密 //请求体中获取密文、请求头中获取签名,然后验签解密,这里直接用上面请求参数reqContent、签名req_sign String reqEncrypt = JSON.parseObject(sb.toString()).get("bizContent").toString();//从请求体中获取密文 String reqGetContent = RSAUtils.checkSignAndDecrypt(reqEncrypt, resp_sign, ZJPT_PUBLIC_KEY, HZHB_PRIVATE_KEY, "UTF-8", true, true); System.out.println("解密后的请求参数reqGetContent=" + reqGetContent); return reqGetContent; } //关闭连接、释放资源 reader.close(); in1.close(); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 发送 SSL POST 请求(HTTPS),JSON形式 * * @param apiUrl API接口URL * @param json JSON对象 * @return */ public static String doPostSSL(String apiUrl, Object json) { CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build(); HttpPost httpPost = new HttpPost(apiUrl); CloseableHttpResponse response = null; String httpStr = null; try { httpPost.setConfig(requestConfig); StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");//解决中文乱码问题 stringEntity.setContentEncoding("UTF-8"); stringEntity.setContentType("application/json"); httpPost.setEntity(stringEntity); response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { return null; } HttpEntity entity = response.getEntity(); if (entity == null) { return null; } httpStr = EntityUtils.toString(entity, "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } } } return httpStr; } /** * 创建SSL安全连接 * * @return */ private static LayeredConnectionSocketFactory createSSLConnSocketFactory() { SSLConnectionSocketFactory sslsf = null; try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } @Override public void verify(String host, SSLSocket ssl) throws IOException { } @Override public void verify(String host, X509Certificate cert) throws SSLException { } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { } }); } catch (GeneralSecurityException e) { e.printStackTrace(); } return sslsf; } public static HeadMessage HeadMessage(String post) { JSONObject jsonObject = JSONObject.parseObject(post); Map map = jsonObject; String head = map.get("head").toString(); HeadMessage list = JSONObject.parseObject(StringEscapeUtils.unescapeJava(head), HeadMessage.class); return list; } public static void main(String[] args) { try { Date v_startDate = new Date("2021-11-27"); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String startDate = df.format(v_startDate); System.out.println(startDate); } catch (Exception e) { e.printStackTrace(); } } }