HttpClient431Util.java 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. package com.iamberry.wechat.tools;
  2. import java.io.*;
  3. import java.net.HttpURLConnection;
  4. import java.net.URL;
  5. import java.security.KeyManagementException;
  6. import java.security.KeyStore;
  7. import java.security.KeyStoreException;
  8. import java.security.NoSuchAlgorithmException;
  9. import java.security.UnrecoverableKeyException;
  10. import java.security.cert.CertificateException;
  11. import java.security.cert.X509Certificate;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. import java.util.Map;
  15. import javax.net.ssl.SSLContext;
  16. import org.apache.commons.io.FileUtils;
  17. import org.apache.commons.lang.StringUtils;
  18. import org.apache.http.HttpEntity;
  19. import org.apache.http.HttpResponse;
  20. import org.apache.http.NameValuePair;
  21. import org.apache.http.client.HttpClient;
  22. import org.apache.http.client.config.RequestConfig;
  23. import org.apache.http.client.entity.UrlEncodedFormEntity;
  24. import org.apache.http.client.methods.CloseableHttpResponse;
  25. import org.apache.http.client.methods.HttpGet;
  26. import org.apache.http.client.methods.HttpPost;
  27. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  28. import org.apache.http.conn.ssl.SSLContextBuilder;
  29. import org.apache.http.conn.ssl.SSLContexts;
  30. import org.apache.http.conn.ssl.TrustStrategy;
  31. import org.apache.http.entity.ContentType;
  32. import org.apache.http.entity.StringEntity;
  33. import org.apache.http.impl.client.CloseableHttpClient;
  34. import org.apache.http.impl.client.HttpClients;
  35. import org.apache.http.message.BasicNameValuePair;
  36. import org.apache.http.util.EntityUtils;
  37. import org.apache.log4j.Logger;
  38. import com.alibaba.dubbo.common.json.JSONObject;
  39. import com.google.common.base.Strings;
  40. /**
  41. * @author 何秀刚
  42. * Class Description:http请求封装
  43. * Create Date:2016年5月3日
  44. * Update Date:2016年5月3日
  45. */
  46. public class HttpClient431Util {
  47. protected static final Logger log = Logger.getLogger(HttpClient431Util.class);
  48. private static final RequestConfig config;
  49. /**
  50. * 用于单向加密的POST请求的缓存connection
  51. */
  52. public static CloseableHttpClient singleSSLConnection = null;
  53. /**
  54. * 用于缓存双向加密的请求的Connection,通用
  55. */
  56. public static CloseableHttpClient dualSSLConnectionJKS;
  57. /**
  58. * 用于缓存双向加密的请求的Connection by Key,微信支付使用的
  59. */
  60. public static CloseableHttpClient dualSSLConnectionByKey;
  61. static {
  62. config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();
  63. }
  64. public static String doGet( Map<String, String> params,String url,String cookie) throws Exception{
  65. return doGet(params,url,NameUtils.DEFAULT_SEND_CHARSET,NameUtils.DEFAULT_RES_CHARSET,cookie);
  66. }
  67. public static String doGet( Map<String, String> params,String url) throws Exception{
  68. return doGet(params,url,NameUtils.DEFAULT_SEND_CHARSET,NameUtils.DEFAULT_RES_CHARSET,"");
  69. }
  70. public static String doPost(Map<String, String> params,String url) throws Exception{
  71. return doPost(params,url,NameUtils.DEFAULT_SEND_CHARSET,NameUtils.DEFAULT_RES_CHARSET);
  72. }
  73. public static String doDualSSLPost(Map<String, String> params,String url,String keyStorePath,String keyStorePass) throws Exception{
  74. return doDualSSLPost(params, url, NameUtils.DEFAULT_SEND_CHARSET, NameUtils.DEFAULT_RES_CHARSET, keyStorePath, keyStorePass);
  75. }
  76. public static String doDualSSLPost(String params,String url,String keyStorePath,String keyStorePass) throws Exception{
  77. return doDualSSLPost(params, url, NameUtils.DEFAULT_SEND_CHARSET, NameUtils.DEFAULT_RES_CHARSET, keyStorePath, keyStorePass);
  78. }
  79. public static String doGet2( Map<String, String> params,String url,String cookie) throws Exception{
  80. return doGet(params,url,NameUtils.DEFAULT_SEND_CHARSET,NameUtils.DEFAULT_RES_CHARSET,cookie);
  81. }
  82. public static String doPostContent(String dataContent,String contentType,String contentCharset,String resCharset,String url) throws Exception{
  83. CloseableHttpClient httpClient = getSingleSSLConnection();
  84. CloseableHttpResponse response = null;
  85. if(StringUtils.isBlank(url)){
  86. return null;
  87. }
  88. try {
  89. HttpPost httpPost = new HttpPost(url);
  90. httpPost.addHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
  91. httpPost.addHeader("Content-Type", contentType);
  92. httpPost.addHeader("Connection" , "close");
  93. HttpEntity reqentity = new StringEntity(dataContent, ContentType.create(contentType, contentCharset) );
  94. httpPost.setEntity(reqentity);
  95. response = httpClient.execute(httpPost);
  96. int statusCode = response.getStatusLine().getStatusCode();
  97. if (statusCode != 200) {
  98. httpPost.abort();
  99. throw new Exception("HttpClient,error status code :" + statusCode);
  100. }
  101. HttpEntity entity = response.getEntity();
  102. String result = null;
  103. if (entity != null){
  104. result = EntityUtils.toString(entity, resCharset==null?NameUtils.DEFAULT_RES_CHARSET:resCharset);
  105. }
  106. EntityUtils.consume(entity);
  107. return result;
  108. } catch (Exception e) {
  109. throw new Exception(e);
  110. } finally{
  111. if(response!=null)
  112. try {
  113. response.close();
  114. } catch (IOException e) {
  115. }
  116. }
  117. }
  118. public static String doPostContent(String dataContent,String contentType,String url) throws Exception{
  119. CloseableHttpClient httpClient = getSingleSSLConnection();
  120. CloseableHttpResponse response = null;
  121. if(StringUtils.isBlank(url)){
  122. return null;
  123. }
  124. try {
  125. HttpPost httpPost = new HttpPost(url);
  126. httpPost.addHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
  127. httpPost.addHeader("Content-Type", contentType);
  128. httpPost.addHeader("Connection" , "close");
  129. HttpEntity reqentity = new StringEntity(dataContent, ContentType.create(contentType, NameUtils.DEFAULT_RES_CHARSET) );
  130. httpPost.setEntity(reqentity);
  131. response = httpClient.execute(httpPost);
  132. int statusCode = response.getStatusLine().getStatusCode();
  133. if (statusCode != 200) {
  134. httpPost.abort();
  135. throw new Exception("HttpClient,error status code :" + statusCode);
  136. }
  137. HttpEntity entity = response.getEntity();
  138. String result = null;
  139. if (entity != null){
  140. result = EntityUtils.toString(entity, NameUtils.DEFAULT_RES_CHARSET);
  141. }
  142. EntityUtils.consume(entity);
  143. return result;
  144. } catch (Exception e) {
  145. throw new Exception(e);
  146. } finally{
  147. if(response!=null)
  148. try {
  149. response.close();
  150. } catch (IOException e) {
  151. }
  152. }
  153. }
  154. /**
  155. * HTTP Get 获取内容
  156. * @param params 请求的参数
  157. * @param url 请求的url地址 ?之前的地址
  158. * @param reqCharset 编码格式
  159. * @param resCharset 编码格式
  160. * @return 页面内容
  161. * @throws Exception
  162. */
  163. public static String doGet(Map<String,String> params,String url,String reqCharset,String resCharset,String cookie) throws Exception{
  164. CloseableHttpClient httpClient = getSingleSSLConnection();
  165. CloseableHttpResponse response = null;
  166. if(StringUtils.isBlank(url)){
  167. return null;
  168. }
  169. try {
  170. if(params != null && !params.isEmpty()){
  171. List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
  172. for(Map.Entry<String,String> entry : params.entrySet()){
  173. String value = entry.getValue();
  174. if(value != null){
  175. pairs.add(new BasicNameValuePair(entry.getKey(),value));
  176. }
  177. }
  178. url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, reqCharset==null?NameUtils.DEFAULT_SEND_CHARSET:reqCharset));
  179. }
  180. HttpGet httpGet = new HttpGet(url);
  181. httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36");
  182. httpGet.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
  183. httpGet.addHeader("Accept-Encoding","gzip, deflate, br");
  184. httpGet.addHeader("Accept-Language","zh-CN,zh;q=0.9");
  185. httpGet.addHeader("Cache-Control","max-age=0");
  186. httpGet.addHeader("Connection" , "close");
  187. if (!Strings.isNullOrEmpty(cookie)){
  188. httpGet.setHeader("Cookie", cookie);
  189. }
  190. response = httpClient.execute(httpGet);
  191. int statusCode = response.getStatusLine().getStatusCode();
  192. if (statusCode != 200) {
  193. httpGet.abort();
  194. throw new Exception("HttpClient,error status code :" + statusCode);
  195. }
  196. HttpEntity entity = response.getEntity();
  197. String result = null;
  198. if (entity != null){
  199. result = EntityUtils.toString(entity, resCharset==null ? NameUtils.DEFAULT_RES_CHARSET:resCharset);
  200. }
  201. EntityUtils.consume(entity);
  202. response.close();
  203. return result;
  204. } catch (Exception e) {
  205. throw new Exception(e);
  206. } finally{
  207. if(response!=null)
  208. try {
  209. response.close();
  210. } catch (IOException e) {
  211. e.printStackTrace();
  212. }
  213. }
  214. }
  215. /**
  216. * 下载远程文件
  217. * @param url
  218. * @param path
  219. * @return
  220. * @throws Exception
  221. */
  222. public static boolean downloadFile(String url, String path) throws Exception {
  223. CloseableHttpClient httpClient = getSingleSSLConnection();
  224. CloseableHttpResponse response = null;
  225. if(StringUtils.isBlank(url)){
  226. return false;
  227. }
  228. try {
  229. HttpGet httpGet = new HttpGet(url);
  230. httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36");
  231. httpGet.addHeader("Connection" , "close");
  232. response = httpClient.execute(httpGet);
  233. int statusCode = response.getStatusLine().getStatusCode();
  234. if (statusCode != 200) {
  235. httpGet.abort();
  236. throw new Exception("HttpClient,error status code :" + statusCode);
  237. }
  238. byte[] data = EntityUtils.toByteArray(response.getEntity());
  239. try {
  240. // 保存文件
  241. FileUtils.writeByteArrayToFile(new File(path), data);
  242. } catch (Exception e) {
  243. log.error("save File Error, path = " + path + ",url=" + url, e);
  244. } finally {
  245. try {
  246. } catch (Exception e) {
  247. log.error("finally BufferedOutputStream shutdown close", e);
  248. }
  249. }
  250. EntityUtils.consume(response.getEntity());
  251. response.close();
  252. return true;
  253. } catch (Exception e) {
  254. log.error("htt client error.", e);
  255. } finally{
  256. if(response!=null)
  257. try {
  258. response.close();
  259. } catch (IOException e) {
  260. }
  261. }
  262. return false;
  263. }
  264. /**
  265. * HTTP Post 获取内容
  266. * @param params 请求的参数
  267. * @param url 请求的url地址 ?之前的地址
  268. * @param reqCharset 编码格式
  269. * @param resCharset 编码格式
  270. * @return 页面内容
  271. */
  272. public static String doPost(Map<String,String> params,String url,String reqCharset,String resCharset) throws Exception{
  273. CloseableHttpClient httpClient = getSingleSSLConnection();
  274. CloseableHttpResponse response = null;
  275. if(StringUtils.isBlank(url)){
  276. return null;
  277. }
  278. try {
  279. List<NameValuePair> pairs = null;
  280. if(params != null && !params.isEmpty()){
  281. pairs = new ArrayList<NameValuePair>(params.size());
  282. for(Map.Entry<String,String> entry : params.entrySet()){
  283. String value = entry.getValue();
  284. if(value != null){
  285. pairs.add(new BasicNameValuePair(entry.getKey(),value));
  286. }
  287. }
  288. }
  289. HttpPost httpPost = new HttpPost(url);
  290. httpPost.addHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
  291. httpPost.addHeader("Connection" , "close");
  292. if(pairs != null && pairs.size() > 0){
  293. httpPost.setEntity(new UrlEncodedFormEntity(pairs,reqCharset==null?NameUtils.DEFAULT_SEND_CHARSET:reqCharset));
  294. }
  295. response = httpClient.execute(httpPost);
  296. int statusCode = response.getStatusLine().getStatusCode();
  297. if (statusCode != 200) {
  298. httpPost.abort();
  299. throw new Exception("HttpClient,error status code :" + statusCode);
  300. }
  301. HttpEntity entity = response.getEntity();
  302. String result = null;
  303. if (entity != null){
  304. result = EntityUtils.toString(entity, resCharset==null?NameUtils.DEFAULT_RES_CHARSET:resCharset);
  305. }
  306. EntityUtils.consume(entity);
  307. response.close();
  308. return result;
  309. }
  310. catch (Exception e) {
  311. throw e;
  312. }finally{
  313. if(response!=null)
  314. try {
  315. response.close();
  316. } catch (IOException e) {
  317. }
  318. }
  319. }
  320. /**
  321. * HTTP Post 获取内容
  322. * @param params 请求的参数
  323. * @param url 请求的url地址 ?之前的地址
  324. * @param reqCharset 编码格式
  325. * @param resCharset 编码格式
  326. * @return 页面内容
  327. */
  328. public static String doPost(Map<String,String> params,String url,String reqCharset,String resCharset,String contentType) throws Exception{
  329. CloseableHttpClient httpClient = getSingleSSLConnection();
  330. CloseableHttpResponse response = null;
  331. if(StringUtils.isBlank(url)){
  332. return null;
  333. }
  334. try {
  335. List<NameValuePair> pairs = null;
  336. if(params != null && !params.isEmpty()){
  337. pairs = new ArrayList<NameValuePair>(params.size());
  338. for(Map.Entry<String,String> entry : params.entrySet()){
  339. String value = entry.getValue();
  340. if(value != null){
  341. pairs.add(new BasicNameValuePair(entry.getKey(),value));
  342. }
  343. }
  344. }
  345. HttpPost httpPost = new HttpPost(url);
  346. httpPost.addHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
  347. httpPost.addHeader("Content-Type",contentType);
  348. httpPost.addHeader("Connection" , "close");
  349. if(pairs != null && pairs.size() > 0){
  350. httpPost.setEntity(new UrlEncodedFormEntity(pairs,reqCharset==null?NameUtils.DEFAULT_SEND_CHARSET:reqCharset));
  351. }
  352. response = httpClient.execute(httpPost);
  353. int statusCode = response.getStatusLine().getStatusCode();
  354. if (statusCode != 200) {
  355. httpPost.abort();
  356. throw new Exception("HttpClient,error status code :" + statusCode);
  357. }
  358. HttpEntity entity = response.getEntity();
  359. String result = null;
  360. if (entity != null){
  361. result = EntityUtils.toString(entity, resCharset==null?NameUtils.DEFAULT_RES_CHARSET:resCharset);
  362. }
  363. EntityUtils.consume(entity);
  364. response.close();
  365. return result;
  366. } catch (Exception e) {
  367. throw new Exception(e);
  368. } finally{
  369. if(response!=null)
  370. try {
  371. response.close();
  372. } catch (IOException e) {
  373. }
  374. }
  375. }
  376. public static String doPost(JSONObject jsonObject, String url, String resCharset) throws Exception{
  377. CloseableHttpClient httpClient = getSingleSSLConnection();
  378. CloseableHttpResponse response = null;
  379. if(StringUtils.isBlank(url)){
  380. return null;
  381. }
  382. try {
  383. HttpPost httpPost = new HttpPost(url);
  384. httpPost.addHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
  385. httpPost.addHeader("Content-Type","JSON");
  386. httpPost.addHeader("Connection" , "close");
  387. StringEntity myEntity = new StringEntity(jsonObject.toString(), "UTF-8");
  388. httpPost.setEntity(myEntity);
  389. response = httpClient.execute(httpPost);
  390. int statusCode = response.getStatusLine().getStatusCode();
  391. if (statusCode != 200) {
  392. httpPost.abort();
  393. throw new Exception("HttpClient,error status code :" + statusCode);
  394. }
  395. HttpEntity entity = response.getEntity();
  396. String result = null;
  397. if (entity != null){
  398. result = EntityUtils.toString(entity, resCharset==null?NameUtils.DEFAULT_RES_CHARSET:resCharset);
  399. }
  400. EntityUtils.consume(entity);
  401. response.close();
  402. return result;
  403. } catch (Exception e) {
  404. throw new Exception(e);
  405. } finally{
  406. if(response!=null)
  407. try {
  408. response.close();
  409. } catch (IOException e) {
  410. }
  411. }
  412. }
  413. /**
  414. * HTTP Post 获取内容
  415. * @param params 请求的参数
  416. * @param url 请求的url地址 ?之前的地址
  417. * @param reqCharset 编码格式
  418. * @param resCharset 编码格式
  419. * @return 页面内容
  420. * @throws Exception
  421. */
  422. public static String doDualSSLPost(Map<String,String> params,String url,String reqCharset,String resCharset,String keyStorePath,String keyStorePass) throws Exception{
  423. CloseableHttpClient httpClient = getDualSSLConnection(keyStorePath,keyStorePass);
  424. CloseableHttpResponse response = null;
  425. if(StringUtils.isBlank(url)){
  426. return null;
  427. }
  428. try {
  429. List<NameValuePair> pairs = null;
  430. if(params != null && !params.isEmpty()){
  431. pairs = new ArrayList<NameValuePair>(params.size());
  432. for(Map.Entry<String,String> entry : params.entrySet()){
  433. String value = entry.getValue();
  434. if(value != null){
  435. pairs.add(new BasicNameValuePair(entry.getKey(),value));
  436. }
  437. }
  438. }
  439. HttpPost httpPost = new HttpPost(url);
  440. httpPost.addHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
  441. httpPost.addHeader("Connection" , "close");
  442. if(pairs != null && pairs.size() > 0){
  443. httpPost.setEntity(new UrlEncodedFormEntity(pairs,reqCharset==null?NameUtils.DEFAULT_SEND_CHARSET:reqCharset));
  444. }
  445. response = httpClient.execute(httpPost);
  446. int statusCode = response.getStatusLine().getStatusCode();
  447. if (statusCode != 200) {
  448. httpPost.abort();
  449. throw new Exception("HttpClient,error status code :" + statusCode);
  450. }
  451. HttpEntity entity = response.getEntity();
  452. String result = null;
  453. if (entity != null){
  454. result = EntityUtils.toString(entity, resCharset==null?NameUtils.DEFAULT_RES_CHARSET:resCharset);
  455. }
  456. EntityUtils.consume(entity);
  457. response.close();
  458. return result;
  459. } catch (Exception e) {
  460. throw new Exception(e);
  461. } finally{
  462. if(response!=null)
  463. try {
  464. response.close();
  465. } catch (IOException e) {
  466. }
  467. }
  468. }
  469. /**
  470. * HTTP Post 获取内容
  471. * @param params 请求的参数
  472. * @param url 请求的url地址 ?之前的地址
  473. * @param reqCharset 编码格式
  474. * @param resCharset 编码格式
  475. * @return 页面内容
  476. * @throws Exception
  477. */
  478. public static String doDualSSLPost(String params,String url,String reqCharset,String resCharset,String keyStorePath,String keyStorePass) throws Exception{
  479. CloseableHttpClient httpClient = getDualSSLConnection(keyStorePath,keyStorePass);
  480. CloseableHttpResponse response = null;
  481. if(StringUtils.isBlank(url)){
  482. return null;
  483. }
  484. try {
  485. HttpPost httpPost = new HttpPost(url);
  486. httpPost.addHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
  487. httpPost.addHeader("Connection" , "close");
  488. httpPost.setEntity(new StringEntity(params, "UTF-8"));
  489. response = httpClient.execute(httpPost);
  490. int statusCode = response.getStatusLine().getStatusCode();
  491. if (statusCode != 200) {
  492. httpPost.abort();
  493. throw new Exception("HttpClient,error status code :" + statusCode);
  494. }
  495. HttpEntity entity = response.getEntity();
  496. String result = null;
  497. if (entity != null){
  498. result = EntityUtils.toString(entity, resCharset==null?NameUtils.DEFAULT_RES_CHARSET:resCharset);
  499. }
  500. EntityUtils.consume(entity);
  501. response.close();
  502. return result;
  503. } catch (Exception e) {
  504. throw new Exception(e);
  505. } finally{
  506. if(response!=null)
  507. try {
  508. response.close();
  509. } catch (IOException e) {
  510. }
  511. }
  512. }
  513. /**
  514. * 创建双向ssl的连接
  515. * @param keyStorePath
  516. * @param keyStorePass
  517. * @return
  518. * @throws Exception
  519. */
  520. private static CloseableHttpClient getDualSSLConnection(String keyStorePath,String keyStorePass) throws Exception{
  521. if (HttpClient431Util.dualSSLConnectionJKS != null) {
  522. return HttpClient431Util.dualSSLConnectionJKS;
  523. }
  524. CloseableHttpClient httpClient = null;
  525. try {
  526. File file = new File(keyStorePath);
  527. URL sslJksUrl = file.toURI().toURL();
  528. KeyStore keyStore = KeyStore.getInstance("jks");
  529. InputStream is = null;
  530. try {
  531. is = sslJksUrl.openStream();
  532. keyStore.load(is, keyStorePass != null ? keyStorePass.toCharArray(): null);
  533. } finally {
  534. if (is != null) is.close();
  535. }
  536. SSLContext sslContext = new SSLContextBuilder().loadKeyMaterial(keyStore, keyStorePass != null ? keyStorePass.toCharArray(): null)
  537. .loadTrustMaterial(null,new TrustStrategy() {
  538. @Override
  539. public boolean isTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException {return true;}
  540. })
  541. .build();
  542. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  543. httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(config).build();
  544. HttpClient431Util.dualSSLConnectionJKS = httpClient;
  545. return httpClient;
  546. } catch (Exception e) {
  547. throw new Exception(e);
  548. }
  549. }
  550. /**
  551. * 创建双向ssl的连接
  552. * @param keyStorePath
  553. * @param keyStorePass
  554. * @return
  555. * @throws Exception
  556. */
  557. private static CloseableHttpClient getSendDualSSLConnection(String keyStorePath,String keyStorePass) throws Exception{
  558. if (HttpClient431Util.dualSSLConnectionByKey != null) {
  559. return HttpClient431Util.dualSSLConnectionByKey;
  560. }
  561. CloseableHttpClient httpClient = null;
  562. try {
  563. InputStream is = null;
  564. try {
  565. is = StaticInfo.sslJksUrl.openStream();
  566. StaticInfo.keyStore.load(is, keyStorePass != null ? keyStorePass.toCharArray(): null);
  567. } finally {
  568. if (is != null) is.close();
  569. }
  570. SSLContext sslContext = new SSLContextBuilder().loadKeyMaterial(StaticInfo.keyStore, keyStorePass != null ? keyStorePass.toCharArray(): null)
  571. .loadTrustMaterial(null,new TrustStrategy() {
  572. @Override
  573. public boolean isTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException {return true;}
  574. }).build();
  575. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  576. httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(config).build();
  577. HttpClient431Util.dualSSLConnectionByKey = httpClient;
  578. return httpClient;
  579. } catch (Exception e) {
  580. throw new Exception(e);
  581. }
  582. }
  583. /**
  584. * 获取一个SSL加密的socket
  585. */
  586. public static CloseableHttpClient getHttpClient() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException, UnrecoverableKeyException {
  587. KeyStore keyStore = KeyStore.getInstance("PKCS12");
  588. InputStream instream = MoneyUtils.class.getResourceAsStream("/apiclient_cert.p12");
  589. try {
  590. keyStore.load(instream, NameUtils.getConfig("KEYSTORE_PASSWORD").toCharArray());// 这里写密码..默认是你的MCHID
  591. } finally {
  592. instream.close();
  593. }
  594. SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, NameUtils.getConfig("KEYSTORE_PASSWORD").toCharArray()).build();
  595. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
  596. return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(config).build();
  597. }
  598. /**
  599. * HTTP Post 获取内容
  600. * @param params 请求的参数
  601. * @param url 请求的url地址 ?之前的地址
  602. * @param reqCharset 编码格式
  603. * @param resCharset 编码格式
  604. * @return 页面内容
  605. */
  606. public static String doSendWechatRedPack(Map<String, Object> params,String url,String reqCharset,String resCharset,String contentType) throws Exception{
  607. CloseableHttpClient httpClient = getSendDualSSLConnection(StaticInfo.getResourcekey(), NameUtils.getConfig("KEYSTORE_PASSWORD"));
  608. CloseableHttpResponse response = null;
  609. if(StringUtils.isBlank(url)){
  610. return null;
  611. }
  612. try {
  613. HttpPost httpPost = new HttpPost(url);
  614. httpPost.addHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
  615. httpPost.addHeader("Content-Type",contentType);
  616. httpPost.addHeader("Connection" , "close");
  617. httpPost.setEntity(new StringEntity(MoneyUtils.createXML(params), "UTF-8"));
  618. response = httpClient.execute(httpPost);
  619. int statusCode = response.getStatusLine().getStatusCode();
  620. if (statusCode != 200) {
  621. httpPost.abort();
  622. throw new Exception("HttpClient,error status code :" + statusCode);
  623. }
  624. HttpEntity entity = response.getEntity();
  625. String result = null;
  626. if (entity != null){
  627. result = EntityUtils.toString(entity, resCharset==null?NameUtils.DEFAULT_RES_CHARSET:resCharset);
  628. }
  629. EntityUtils.consume(entity);
  630. response.close();
  631. return result;
  632. } catch (Exception e) {
  633. throw new Exception(e);
  634. } finally{
  635. if(response!=null)
  636. try {
  637. response.close();
  638. } catch (IOException e) {
  639. }
  640. }
  641. }
  642. /**
  643. * 创建单向ssl的连接
  644. * @return
  645. * @throws Exception
  646. */
  647. private static CloseableHttpClient getSingleSSLConnection() throws Exception{
  648. if (singleSSLConnection != null) {
  649. return singleSSLConnection;
  650. }
  651. CloseableHttpClient httpClient = null;
  652. try {
  653. SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,new TrustStrategy() {
  654. @Override
  655. public boolean isTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException {
  656. return true;
  657. }
  658. }).build();
  659. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
  660. httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(config).build();
  661. HttpClient431Util.singleSSLConnection = httpClient;
  662. return httpClient;
  663. } catch (Exception e) {
  664. throw new Exception(e);
  665. }
  666. }
  667. public static String sendXmlData(String url,Map<String,String> params) throws Exception{
  668. HttpClient client = HttpClients.createDefault();
  669. // client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,true);
  670. List<NameValuePair> pairs = null;
  671. if(params != null && !params.isEmpty()){
  672. pairs = new ArrayList<NameValuePair>(params.size());
  673. for(Map.Entry<String,String> entry : params.entrySet()){
  674. String value = entry.getValue();
  675. if(value != null){
  676. pairs.add(new BasicNameValuePair(entry.getKey(),value));
  677. }
  678. }
  679. }
  680. HttpPost post = new HttpPost(url);
  681. post.setHeader("Content-Type","text/xml;charset=GB2312");
  682. post.setEntity(new UrlEncodedFormEntity(pairs,"GB2312"));
  683. HttpResponse response = client.execute(post);
  684. Integer code = response.getStatusLine().getStatusCode();
  685. if(code == 200){
  686. String result = EntityUtils.toString(response.getEntity(), "GB18030");
  687. EntityUtils.consume(response.getEntity());
  688. post.abort();
  689. return result;
  690. }
  691. return "";
  692. }
  693. public static void main(String[] args) throws Exception {
  694. // long start = System.currentTimeMillis();
  695. // boolean b = downloadFile("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQHT8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xLzgwamFXRURsc3AzTE1pQnoxbUFfAAIEkhQsVwMEAAAAAA%3D%3D", "D://abcdefgj.png");
  696. // long end = System.currentTimeMillis();
  697. // System.out.println(b + "," + (end - start));
  698. // 生成系统级请求数据
  699. // Map<String, String> params = new HashMap<String, String>();
  700. // params.put("nu", "221435993148");
  701. // String url = "http://api.open.baidu.com/pae/common/api/Redirect";
  702. // // 发送请求
  703. // String html = HttpClient431Util.doGet(params, url);
  704. // Document doc = Jsoup.parse(html);
  705. // Element content = doc.getElementById("companyCode");
  706. // String value = content.val();
  707. }
  708. }