HttpsPostUtil.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. package com.ydtech.utils;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.ydtech.modules.nai.httpvo.HeadMessage;
  5. import com.ydtech.utils.RSA.RSAUtils;
  6. import org.apache.commons.text.StringEscapeUtils;
  7. import org.apache.http.HttpEntity;
  8. import org.apache.http.HttpStatus;
  9. import org.apache.http.client.config.RequestConfig;
  10. import org.apache.http.client.methods.CloseableHttpResponse;
  11. import org.apache.http.client.methods.HttpPost;
  12. import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
  13. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  14. import org.apache.http.conn.ssl.TrustStrategy;
  15. import org.apache.http.conn.ssl.X509HostnameVerifier;
  16. import org.apache.http.entity.StringEntity;
  17. import org.apache.http.impl.client.CloseableHttpClient;
  18. import org.apache.http.impl.client.HttpClients;
  19. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  20. import org.apache.http.ssl.SSLContextBuilder;
  21. import org.apache.http.util.EntityUtils;
  22. import javax.net.ssl.*;
  23. import java.io.*;
  24. import java.net.HttpURLConnection;
  25. import java.net.URL;
  26. import java.security.GeneralSecurityException;
  27. import java.security.cert.CertificateException;
  28. import java.security.cert.X509Certificate;
  29. import java.text.SimpleDateFormat;
  30. import java.util.Date;
  31. import java.util.HashMap;
  32. import java.util.Map;
  33. /**
  34. * @ClassName HttpsPostUtil
  35. * @Description: TODO
  36. * @Author
  37. * @Date 2021/5/24
  38. **/
  39. public class HttpsPostUtil {
  40. private static RequestConfig requestConfig;
  41. private static PoolingHttpClientConnectionManager connMgr;
  42. private static final int MAX_TIMEOUT = 7000;
  43. static {
  44. // 设置连接池
  45. connMgr = new PoolingHttpClientConnectionManager();
  46. // 设置连接池大小
  47. connMgr.setMaxTotal(100);
  48. connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
  49. RequestConfig.Builder configBuilder = RequestConfig.custom();
  50. // 设置连接超时
  51. configBuilder.setConnectTimeout(MAX_TIMEOUT);
  52. // 设置读取超时
  53. configBuilder.setSocketTimeout(MAX_TIMEOUT);
  54. // 设置从连接池获取连接实例的超时
  55. configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
  56. // 在提交请求之前 测试连接是否可用
  57. configBuilder.setStaleConnectionCheckEnabled(true);
  58. requestConfig = configBuilder.build();
  59. }
  60. //添加主机名验证程序类,设置不验证主机
  61. private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
  62. @Override
  63. public boolean verify(String hostname, SSLSession session) {
  64. return true;
  65. }
  66. };
  67. //添加信任主机
  68. private static void trustAllHosts() {
  69. // 创建不验证证书链的信任管理器 这里使用的是x509证书
  70. TrustManager[] trustAllCerts = new TrustManager[]{new MyX509TrustManager() {
  71. @Override
  72. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  73. return new java.security.cert.X509Certificate[]{};
  74. }
  75. @Override
  76. public void checkClientTrusted(X509Certificate[] chain, String authType) {
  77. }
  78. @Override
  79. public void checkServerTrusted(X509Certificate[] chain, String authType) {
  80. }
  81. }};
  82. // 安装所有信任的信任管理器
  83. try {
  84. SSLContext sc = SSLContext.getInstance("TLS");
  85. sc.init(null, trustAllCerts, new java.security.SecureRandom());
  86. //HttpsURLConnection通过SSLSocket来建立与HTTPS的安全连接,SSLSocket对象是由SSLSocketFactory生成的。
  87. HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  88. } catch (Exception e) {
  89. e.printStackTrace();
  90. }
  91. }
  92. public static String sendPost(String urls, String param) {
  93. @SuppressWarnings("unused")
  94. JSONObject jsonObject = null;
  95. StringBuffer sb = new StringBuffer();
  96. try {
  97. //建立连接
  98. URL url = new URL(urls);
  99. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  100. connection.setDoOutput(true);
  101. connection.setDoInput(true);
  102. connection.setUseCaches(false);
  103. // connection.setRequestMethod(RequestMethod);
  104. //设置请求内容编码格式
  105. connection.setRequestProperty("content-type", "application/json;charset=UTF-8");
  106. connection.setRequestProperty("Accept", "application/json;charset=UTF-8");
  107. connection.setConnectTimeout(60000);
  108. connection.setReadTimeout(60000);
  109. if (param != null) {
  110. OutputStream out = connection.getOutputStream();
  111. out.write(param.getBytes("UTF-8"));
  112. out.close();
  113. }
  114. //流处理
  115. InputStream in1 = connection.getInputStream();
  116. // InputStreamReader inputReader = new InputStreamReader(input,"UTF-8");
  117. BufferedReader reader = new BufferedReader(new InputStreamReader(in1, "GBK"));
  118. // 请求返回的状态
  119. if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
  120. // 请求返回的数据
  121. in1 = connection.getInputStream();
  122. String lines;
  123. reader = new BufferedReader(new InputStreamReader(in1, "GBK"));
  124. while ((lines = reader.readLine()) != null) {
  125. sb.append(lines).append("\n");
  126. }
  127. return sb.toString();
  128. } else {
  129. }
  130. //关闭连接、释放资源
  131. reader.close();
  132. in1.close();
  133. connection.disconnect();
  134. } catch (Exception e) {
  135. }
  136. return null;
  137. }
  138. public static String sendCBITPost_self(String urls, String param) {
  139. @SuppressWarnings("unused")
  140. JSONObject jsonObject = null;
  141. StringBuffer sb = new StringBuffer();
  142. try {
  143. //建立连接
  144. URL url = new URL(urls);
  145. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  146. connection.setDoOutput(true);
  147. connection.setDoInput(true);
  148. connection.setUseCaches(false);
  149. // connection.setRequestMethod(RequestMethod);
  150. //设置请求内容编码格式
  151. connection.setRequestProperty("content-type", "application/json;charset=UTF-8");
  152. connection.setRequestProperty("Accept", "application/json;charset=UTF-8");
  153. connection.setConnectTimeout(60000);
  154. connection.setReadTimeout(60000);
  155. if (param != null) {
  156. OutputStream out = connection.getOutputStream();
  157. out.write(param.getBytes("UTF-8"));
  158. out.close();
  159. }
  160. //流处理
  161. InputStream in1 = connection.getInputStream();
  162. // InputStreamReader inputReader = new InputStreamReader(input,"UTF-8");
  163. BufferedReader reader = null;
  164. // 请求返回的状态
  165. if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
  166. // 请求返回的数据
  167. in1 = connection.getInputStream();
  168. String lines;
  169. reader = new BufferedReader(new InputStreamReader(in1, "UTF-8"));
  170. while ((lines = reader.readLine()) != null) {
  171. sb.append(lines).append("\n");
  172. }
  173. return sb.toString();
  174. } else {
  175. }
  176. //关闭连接、释放资源
  177. reader.close();
  178. in1.close();
  179. connection.disconnect();
  180. } catch (Exception e) {
  181. }
  182. return null;
  183. }
  184. public static String sendCBITPost(String urls, String param, String ZJPT_PUBLIC_KEY, String HZHB_PRIVATE_KEY) {
  185. @SuppressWarnings("unused")
  186. JSONObject jsonObject = null;
  187. StringBuffer sb = new StringBuffer();
  188. try {
  189. //加密加签
  190. //调用工具类加密加签,获取密文和签名
  191. Map<String, String> encry = RSAUtils.encryptAndSign(param, ZJPT_PUBLIC_KEY, HZHB_PRIVATE_KEY, "UTF-8", true, true);
  192. String req_content = encry.get("CONTENT");//密文
  193. System.out.println("加密后的请求参数req_content=" + req_content);
  194. String req_sign = encry.get("SIGNATURE");//签名,放在请求头中
  195. System.out.println("最终请求头中的签名req_sign=" + req_sign);
  196. Map<String, String> reqMap = new HashMap<>();
  197. reqMap.put("bizContent", req_content);//bizContent作为key,密文作为value,转json
  198. String reqContent = JSON.toJSONString(reqMap);//请求入参,放在请求体中
  199. System.out.println("最终请求体中的请求参数reqContent=" + reqContent);
  200. //建立连接
  201. URL url = new URL(urls);
  202. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  203. connection.setDoOutput(true);
  204. connection.setDoInput(true);
  205. connection.setUseCaches(false);
  206. // connection.setRequestMethod(RequestMethod);
  207. //设置请求内容编码格式
  208. connection.setRequestProperty("content-type", "application/json;charset=utf-8");
  209. connection.setRequestProperty("Accept", "application/json;charset=utf-8");
  210. connection.setRequestProperty("Signature", req_sign);
  211. connection.setRequestProperty("PartnerCode", "p_taiyuantianqin");
  212. connection.setConnectTimeout(60000);
  213. connection.setReadTimeout(60000);
  214. if (reqContent != null) {
  215. OutputStream out = connection.getOutputStream();
  216. out.write(reqContent.getBytes("UTF-8"));
  217. out.close();
  218. }
  219. //流处理
  220. InputStream in1 = connection.getInputStream();
  221. BufferedReader reader = new BufferedReader(new InputStreamReader(in1, "GBK"));
  222. // 请求返回的状态
  223. if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
  224. // 请求返回的数据
  225. in1 = connection.getInputStream();
  226. String lines;
  227. reader = new BufferedReader(new InputStreamReader(in1, "GBK"));
  228. while ((lines = reader.readLine()) != null) {
  229. sb.append(lines).append("\n");
  230. }
  231. String resp_sign = connection.getHeaderField("Signature");
  232. //验签解密
  233. //请求体中获取密文、请求头中获取签名,然后验签解密,这里直接用上面请求参数reqContent、签名req_sign
  234. String reqEncrypt = JSON.parseObject(sb.toString()).get("bizContent").toString();//从请求体中获取密文
  235. String reqGetContent = RSAUtils.checkSignAndDecrypt(reqEncrypt, resp_sign, ZJPT_PUBLIC_KEY, HZHB_PRIVATE_KEY, "UTF-8", true, true);
  236. System.out.println("解密后的请求参数reqGetContent=" + reqGetContent);
  237. return reqGetContent;
  238. }
  239. //关闭连接、释放资源
  240. reader.close();
  241. in1.close();
  242. connection.disconnect();
  243. } catch (Exception e) {
  244. e.printStackTrace();
  245. }
  246. return null;
  247. }
  248. /**
  249. * 发送 SSL POST 请求(HTTPS),JSON形式
  250. *
  251. * @param apiUrl API接口URL
  252. * @param json JSON对象
  253. * @return
  254. */
  255. public static String doPostSSL(String apiUrl, Object json) {
  256. CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
  257. HttpPost httpPost = new HttpPost(apiUrl);
  258. CloseableHttpResponse response = null;
  259. String httpStr = null;
  260. try {
  261. httpPost.setConfig(requestConfig);
  262. StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");//解决中文乱码问题
  263. stringEntity.setContentEncoding("UTF-8");
  264. stringEntity.setContentType("application/json");
  265. httpPost.setEntity(stringEntity);
  266. response = httpClient.execute(httpPost);
  267. int statusCode = response.getStatusLine().getStatusCode();
  268. if (statusCode != HttpStatus.SC_OK) {
  269. return null;
  270. }
  271. HttpEntity entity = response.getEntity();
  272. if (entity == null) {
  273. return null;
  274. }
  275. httpStr = EntityUtils.toString(entity, "utf-8");
  276. } catch (Exception e) {
  277. e.printStackTrace();
  278. } finally {
  279. if (response != null) {
  280. try {
  281. EntityUtils.consume(response.getEntity());
  282. } catch (IOException e) {
  283. e.printStackTrace();
  284. }
  285. }
  286. }
  287. return httpStr;
  288. }
  289. /**
  290. * 创建SSL安全连接
  291. *
  292. * @return
  293. */
  294. private static LayeredConnectionSocketFactory createSSLConnSocketFactory() {
  295. SSLConnectionSocketFactory sslsf = null;
  296. try {
  297. SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
  298. @Override
  299. public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  300. return true;
  301. }
  302. }).build();
  303. sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
  304. @Override
  305. public boolean verify(String arg0, SSLSession arg1) {
  306. return true;
  307. }
  308. @Override
  309. public void verify(String host, SSLSocket ssl) throws IOException {
  310. }
  311. @Override
  312. public void verify(String host, X509Certificate cert) throws SSLException {
  313. }
  314. @Override
  315. public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
  316. }
  317. });
  318. } catch (GeneralSecurityException e) {
  319. e.printStackTrace();
  320. }
  321. return sslsf;
  322. }
  323. public static HeadMessage HeadMessage(String post) {
  324. JSONObject jsonObject = JSONObject.parseObject(post);
  325. Map<String, Object> map = jsonObject;
  326. String head = map.get("head").toString();
  327. HeadMessage list = JSONObject.parseObject(StringEscapeUtils.unescapeJava(head), HeadMessage.class);
  328. return list;
  329. }
  330. public static void main(String[] args) {
  331. try {
  332. Date v_startDate = new Date("2021-11-27");
  333. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  334. String startDate = df.format(v_startDate);
  335. System.out.println(startDate);
  336. } catch (Exception e) {
  337. e.printStackTrace();
  338. }
  339. }
  340. }