后台服务
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

656 lines
23 KiB

  1. package com.iformall.utils;
  2. import okhttp3.MediaType;
  3. import okhttp3.OkHttpClient;
  4. import okhttp3.Request;
  5. import okhttp3.RequestBody;
  6. import org.apache.commons.io.IOUtils;
  7. import org.apache.http.*;
  8. import org.apache.http.client.CookieStore;
  9. import org.apache.http.client.config.RequestConfig;
  10. import org.apache.http.client.entity.UrlEncodedFormEntity;
  11. import org.apache.http.client.methods.CloseableHttpResponse;
  12. import org.apache.http.client.methods.HttpGet;
  13. import org.apache.http.client.methods.HttpPost;
  14. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  15. import org.apache.http.entity.StringEntity;
  16. import org.apache.http.impl.client.BasicCookieStore;
  17. import org.apache.http.impl.client.CloseableHttpClient;
  18. import org.apache.http.impl.client.HttpClients;
  19. import org.apache.http.message.BasicNameValuePair;
  20. import org.apache.http.protocol.HTTP;
  21. import org.apache.http.ssl.SSLContexts;
  22. import org.apache.http.util.EntityUtils;
  23. import org.slf4j.Logger;
  24. import org.slf4j.LoggerFactory;
  25. import com.github.binarywang.wxpay.service.WxPayService;
  26. import cn.binarywang.wx.miniapp.api.WxMaService;
  27. import javax.net.ssl.HttpsURLConnection;
  28. import javax.net.ssl.KeyManager;
  29. import javax.net.ssl.KeyManagerFactory;
  30. import javax.net.ssl.SSLContext;
  31. import java.io.*;
  32. import java.net.URI;
  33. import java.net.URL;
  34. import java.nio.charset.Charset;
  35. import java.security.KeyManagementException;
  36. import java.security.KeyStore;
  37. import java.security.KeyStoreException;
  38. import java.security.NoSuchAlgorithmException;
  39. import java.security.SecureRandom;
  40. import java.security.UnrecoverableKeyException;
  41. import java.security.cert.CertificateException;
  42. import java.util.*;
  43. import java.util.concurrent.ConcurrentHashMap;
  44. /**
  45. * @author
  46. * @date
  47. * HttpClient工具类
  48. */
  49. public class HttpUtil {
  50. private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
  51. private static final MediaType CONTENT_TYPE_FORM = MediaType.parse("application/x-www-form-urlencoded");
  52. private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36";
  53. // /**
  54. // * get请求
  55. // * @return
  56. // */
  57. // public static String doGet(String url) {
  58. // try {
  59. // CloseableHttpClient client = HttpClients.createDefault();
  60. // //发送get请求
  61. // HttpGet request = new HttpGet(url);
  62. // HttpResponse response = client.execute(request);
  63. //
  64. // /**请求发送成功,并得到响应**/
  65. // if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  66. // /**读取服务器返回过来的json字符串数据**/
  67. // String strResult = EntityUtils.toString(response.getEntity());
  68. //
  69. // return strResult;
  70. // }
  71. // }
  72. // catch (IOException e) {
  73. // logger.error(e.getMessage());
  74. // throw new RuntimeException(e);
  75. // }
  76. //
  77. // return null;
  78. // }
  79. /**
  80. * get请求
  81. * @return
  82. */
  83. public static byte[] doWiwidePicGet(String url, String signature) {
  84. try {
  85. CloseableHttpClient client = HttpClients.createDefault();
  86. //发送get请求
  87. HttpGet request = new HttpGet(url);
  88. request.setHeader("Cookie", "Signature="+signature);
  89. HttpResponse response = client.execute(request);
  90. /**请求发送成功,并得到响应**/
  91. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  92. /**读取服务器返回过来的json字符串数据**/
  93. byte[] bytes = EntityUtils.toByteArray(response.getEntity());
  94. return bytes;
  95. }
  96. }
  97. catch (IOException e) {
  98. logger.error(e.getMessage());
  99. throw new RuntimeException(e);
  100. }
  101. return null;
  102. }
  103. /**
  104. * post请求(用于key-value格式的参数)
  105. * @param url
  106. * @param params
  107. * @return
  108. */
  109. public static String doPost(String url, Map params){
  110. // 定义HttpClient
  111. CloseableHttpClient client = HttpClients.createDefault();
  112. BufferedReader in = null;
  113. try {
  114. // 实例化HTTP方法
  115. HttpPost request = new HttpPost();
  116. request.setURI(new URI(url));
  117. //设置参数
  118. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  119. for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
  120. String name = (String) iter.next();
  121. String value = String.valueOf(params.get(name));
  122. nvps.add(new BasicNameValuePair(name, value));
  123. //System.out.println(name +"-"+value);
  124. }
  125. request.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
  126. HttpResponse response = client.execute(request);
  127. int code = response.getStatusLine().getStatusCode();
  128. if(code == 200){ //请求成功
  129. in = new BufferedReader(new InputStreamReader(response.getEntity()
  130. .getContent(),"utf-8"));
  131. StringBuilder sb = new StringBuilder("");
  132. String line = "";
  133. String NL = System.getProperty("line.separator");
  134. while ((line = in.readLine()) != null) {
  135. sb.append(line + NL);
  136. }
  137. in.close();
  138. client.close();
  139. return sb.toString();
  140. }
  141. else{ //
  142. logger.info("状态码:" + code);
  143. client.close();
  144. }
  145. }
  146. catch(Exception e){
  147. logger.error(e.getMessage());
  148. return null;
  149. }
  150. return null;
  151. }
  152. // /**
  153. // * post请求(用于key-value格式的参数)
  154. // * @param url
  155. // * @param params
  156. // * @return
  157. // */
  158. // public static String doPost(String url,Map<String,String> headMap, Map params){
  159. //
  160. // // 定义HttpClient
  161. // CloseableHttpClient client = HttpClients.createDefault();
  162. //
  163. // BufferedReader in = null;
  164. // try {
  165. //
  166. // // 实例化HTTP方法
  167. // HttpPost request = new HttpPost();
  168. // request.setURI(new URI(url));
  169. // if(headMap != null){
  170. // Set<String> set = headMap.keySet();
  171. // for(String key: set){
  172. // request.addHeader(key,headMap.get(key));
  173. // }
  174. // }
  175. //
  176. // //设置参数
  177. // List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  178. // for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
  179. // String name = (String) iter.next();
  180. // String value = String.valueOf(params.get(name));
  181. // nvps.add(new BasicNameValuePair(name, value));
  182. //
  183. // //System.out.println(name +"-"+value);
  184. // }
  185. // request.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
  186. //
  187. // HttpResponse response = client.execute(request);
  188. // int code = response.getStatusLine().getStatusCode();
  189. // if(code == 200){ //请求成功
  190. // in = new BufferedReader(new InputStreamReader(response.getEntity()
  191. // .getContent(),"utf-8"));
  192. // StringBuilder sb = new StringBuilder("");
  193. // String line = "";
  194. // String NL = System.getProperty("line.separator");
  195. // while ((line = in.readLine()) != null) {
  196. // sb.append(line + NL);
  197. // }
  198. //
  199. // in.close();
  200. //
  201. // client.close();
  202. //
  203. // return sb.toString();
  204. // }
  205. // else{ //
  206. // logger.info("状态码:" + code);
  207. // client.close();
  208. // }
  209. // }
  210. // catch(Exception e){
  211. // logger.error(e.getMessage());
  212. // return null;
  213. // }
  214. //
  215. // return null;
  216. // }
  217. /**
  218. * post请求(用于key-value格式的参数,wiwide)
  219. * @param url
  220. * @param params
  221. * @return
  222. */
  223. public static String doPostWiwide(String url, String token, Map params){
  224. //CookieStore store= new BasicCookieStore();
  225. //HttpClients.custom().setDefaultCookieStore(store).build();
  226. // 定义HttpClient
  227. CloseableHttpClient client = HttpClients.createDefault();
  228. BufferedReader in = null;
  229. try {
  230. // 实例化HTTP方法
  231. HttpPost request = new HttpPost();
  232. request.setURI(new URI(url));
  233. request.setHeader("Content-Type", "application/x-www-form-urlencoded");
  234. request.setHeader("Accept-Charset", "utf-8");
  235. request.setHeader("wiwidefumaotoken", token);
  236. //设置参数
  237. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  238. for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
  239. String name = (String) iter.next();
  240. String value = String.valueOf(params.get(name));
  241. nvps.add(new BasicNameValuePair(name, value));
  242. //System.out.println(name +"-"+value);
  243. }
  244. request.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
  245. HttpResponse response = client.execute(request);
  246. int code = response.getStatusLine().getStatusCode();
  247. if(code == 200){ //请求成功
  248. in = new BufferedReader(new InputStreamReader(response.getEntity()
  249. .getContent(),"utf-8"));
  250. StringBuilder sb = new StringBuilder("");
  251. String line = "";
  252. String NL = System.getProperty("line.separator");
  253. while ((line = in.readLine()) != null) {
  254. sb.append(line + NL);
  255. }
  256. in.close();
  257. client.close();
  258. return sb.toString();
  259. }
  260. else{ //
  261. logger.info("状态码:" + code);
  262. client.close();
  263. }
  264. }
  265. catch(Exception e){
  266. logger.error(e.getMessage());
  267. return null;
  268. }
  269. return null;
  270. }
  271. /**
  272. * post请求(用于key-value格式的参数,wiwide)
  273. * @param url
  274. * @param params
  275. * @return
  276. */
  277. public static String doPostWiwideNew(String url, String signature, Map params){
  278. //CookieStore store= new BasicCookieStore();
  279. //HttpClients.custom().setDefaultCookieStore(store).build();
  280. // 定义HttpClient
  281. CloseableHttpClient client = HttpClients.createDefault();
  282. BufferedReader in = null;
  283. try {
  284. // 实例化HTTP方法
  285. HttpPost request = new HttpPost();
  286. request.setURI(new URI(url));
  287. request.setHeader("Content-Type", "application/x-www-form-urlencoded");
  288. request.setHeader("Accept-Charset", "utf-8");
  289. request.setHeader("Cookie", "Signature="+signature);
  290. //设置参数
  291. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  292. for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
  293. String name = (String) iter.next();
  294. String value = String.valueOf(params.get(name));
  295. nvps.add(new BasicNameValuePair(name, value));
  296. //System.out.println(name +"-"+value);
  297. }
  298. request.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
  299. HttpResponse response = client.execute(request);
  300. int code = response.getStatusLine().getStatusCode();
  301. if(code == 200){ //请求成功
  302. in = new BufferedReader(new InputStreamReader(response.getEntity()
  303. .getContent(),"utf-8"));
  304. StringBuilder sb = new StringBuilder("");
  305. String line = "";
  306. String NL = System.getProperty("line.separator");
  307. while ((line = in.readLine()) != null) {
  308. sb.append(line + NL);
  309. }
  310. in.close();
  311. client.close();
  312. return sb.toString();
  313. }
  314. else{ //
  315. logger.info("状态码:" + code);
  316. client.close();
  317. }
  318. }
  319. catch(Exception e){
  320. logger.error(e.getMessage());
  321. return null;
  322. }
  323. return null;
  324. }
  325. /**
  326. * post请求(用于请求json格式的参数)
  327. * @param url
  328. * @param params
  329. * @return
  330. */
  331. public static String doPost(String url, Map<String,String> headMap, String params){
  332. CloseableHttpClient httpclient = HttpClients.createDefault();
  333. HttpPost httpPost = new HttpPost(url);// 创建httpPost
  334. httpPost.setHeader("Accept", "application/json");
  335. httpPost.setHeader("Content-Type", "application/json");
  336. if(headMap != null){
  337. Set<String> set = headMap.keySet();
  338. for(String key: set){
  339. httpPost.addHeader(key,headMap.get(key));
  340. }
  341. }
  342. String charSet = "UTF-8";
  343. StringEntity entity = new StringEntity(params, charSet);
  344. httpPost.setEntity(entity);
  345. CloseableHttpResponse response = null;
  346. try {
  347. response = httpclient.execute(httpPost);
  348. StatusLine status = response.getStatusLine();
  349. int state = status.getStatusCode();
  350. if (state == HttpStatus.SC_OK) {
  351. HttpEntity responseEntity = response.getEntity();
  352. String jsonString = EntityUtils.toString(responseEntity);
  353. return jsonString;
  354. }
  355. else{
  356. logger.info("请求返回:"+state+"("+url+")");
  357. }
  358. }
  359. catch(Exception e){
  360. logger.error(e.getMessage());
  361. return null;
  362. }
  363. finally {
  364. if (response != null) {
  365. try {
  366. response.close();
  367. } catch (IOException e) {
  368. logger.error(e.getMessage());
  369. }
  370. }
  371. try {
  372. httpclient.close();
  373. } catch (IOException e) {
  374. logger.error(e.getMessage());
  375. }
  376. }
  377. return null;
  378. }
  379. public static String payPost(String url, String params) {
  380. RequestBody body = RequestBody.create(CONTENT_TYPE_FORM, params);
  381. Request request = null;
  382. try {
  383. request = new Request.Builder().addHeader("Accept-Charset", "utf-8")
  384. .addHeader("Content-Type", "application/x-www-form-urlencoded")
  385. .addHeader("Content-Length", String.valueOf(body.contentLength()))
  386. .url(url).post(body).build();
  387. return exec(request);
  388. } catch (IOException e) {
  389. logger.error(e.getMessage());
  390. return null;
  391. }
  392. }
  393. private static OkHttpClient OkHttpClient = new OkHttpClient();
  394. private static String exec(okhttp3.Request request) {
  395. try {
  396. okhttp3.Response response = OkHttpClient.newCall(request).execute();
  397. // String header = response.header("X-Tt-Logid");
  398. // logger.info("X-Tt-Logid="+header);
  399. if (!response.isSuccessful())
  400. throw new RuntimeException("Unexpected code " + response);
  401. return response.body().string();
  402. } catch (IOException e) {
  403. logger.error(e.getMessage());
  404. throw new RuntimeException(e);
  405. }
  406. }
  407. private static Map<String,SSLContext> sslContextMap = new ConcurrentHashMap<String,SSLContext>();
  408. private static SSLContext getSSLContext(String certPath, String certPass) throws KeyStoreException, NoSuchAlgorithmException,
  409. CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException {
  410. String key = certPath+certPass;
  411. SSLContext sslContext = sslContextMap.get(key);
  412. if ( null == sslContext ) {
  413. synchronized("sslContextLock"+key) {
  414. sslContext = sslContextMap.get(key);
  415. if (null == sslContext) {
  416. KeyStore clientStore = KeyStore.getInstance("PKCS12");
  417. clientStore.load(new FileInputStream(certPath), certPass.toCharArray());
  418. KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
  419. kmf.init(clientStore, certPass.toCharArray());
  420. KeyManager[] kms = kmf.getKeyManagers();
  421. sslContext = SSLContext.getInstance("TLS");
  422. sslContext.init(kms, null, new SecureRandom());
  423. sslContextMap.put(key, sslContext);
  424. }
  425. }
  426. }
  427. return sslContext;
  428. }
  429. public static String payPostSSL(String url, String data, String certPath, String certPass) {
  430. HttpsURLConnection conn = null;
  431. OutputStream out = null;
  432. InputStream inputStream = null;
  433. BufferedReader reader = null;
  434. try {
  435. SSLContext sslContext = getSSLContext(certPath, certPass);
  436. HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
  437. URL _url = new URL(url);
  438. conn = (HttpsURLConnection) _url.openConnection();
  439. conn.setConnectTimeout(25000);
  440. conn.setReadTimeout(25000);
  441. conn.setRequestMethod("POST");
  442. conn.setDoOutput(true);
  443. conn.setDoInput(true);
  444. conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  445. conn.setRequestProperty("User-Agent", DEFAULT_USER_AGENT);
  446. conn.connect();
  447. out = conn.getOutputStream();
  448. out.write(data.getBytes(Charset.forName("UTF-8")));
  449. out.flush();
  450. inputStream = conn.getInputStream();
  451. reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
  452. StringBuilder sb = new StringBuilder();
  453. String line = null;
  454. while ((line = reader.readLine()) != null) {
  455. sb.append(line).append("\n");
  456. }
  457. return sb.toString();
  458. } catch (Exception e) {
  459. logger.error(e.getMessage());
  460. throw new RuntimeException(e);
  461. } finally {
  462. IOUtils.closeQuietly(out);
  463. IOUtils.closeQuietly(reader);
  464. IOUtils.closeQuietly(inputStream);
  465. if (conn != null) {
  466. conn.disconnect();
  467. }
  468. }
  469. }
  470. // private static String ClientCustomSSL(String url, String p12file, String mch_id, String xmlStr) throws Exception{
  471. // KeyStore keyStore = KeyStore.getInstance("PKCS12");
  472. // FileInputStream instream = new FileInputStream(new File(p12file));
  473. // try {
  474. // keyStore.load(instream, mch_id.toCharArray());
  475. // } finally {
  476. // instream.close();
  477. // }
  478. //
  479. // // Trust own CA and all self-signed certs
  480. // SSLContext sslcontext = SSLContexts.custom()
  481. // .loadKeyMaterial(keyStore, mch_id.toCharArray())
  482. // .build();
  483. // // Allow TLSv1 protocol only
  484. // SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
  485. // sslcontext,
  486. // new String[] { "TLSv1" },
  487. // null,
  488. // SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
  489. // CloseableHttpClient httpclient = HttpClients.custom()
  490. // .setSSLSocketFactory(sslsf)
  491. // .build();
  492. // try {
  493. // HttpPost httpPost = new HttpPost(url);
  494. // StringEntity entityStr = new StringEntity(xmlStr);
  495. // entityStr.setContentType("text/xml");
  496. // //logger.info("entityStr--------------"+entityStr);
  497. // httpPost.setEntity(entityStr);
  498. //
  499. // CloseableHttpResponse response = httpclient.execute(httpPost);
  500. // try {
  501. // HttpEntity entity = response.getEntity();
  502. //
  503. // //System.out.println("----------------------------------------");
  504. // //System.out.println(response.getStatusLine());
  505. // if (entity != null) {
  506. // //System.out.println("Response content length: " + entity.getContentLength());
  507. // BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
  508. // StringBuilder sb = new StringBuilder();
  509. // String line = null;
  510. // while ((line = bufferedReader.readLine()) != null) {
  511. // sb.append(line).append("\n");
  512. // }
  513. // return sb.toString();
  514. // }
  515. // EntityUtils.consume(entity);
  516. // } finally {
  517. // response.close();
  518. // }
  519. // } finally {
  520. // httpclient.close();
  521. // return null;
  522. // }
  523. //
  524. // }
  525. /**
  526. * post请求(用于请求json格式的参数)
  527. * @param url
  528. * @param params
  529. * @return
  530. */
  531. public static String doAiVideoPost(String url, String params){
  532. CloseableHttpClient httpclient = HttpClients.createDefault();
  533. HttpPost httpPost = new HttpPost(url);// 创建httpPost
  534. httpPost.setConfig(RequestConfig.custom()
  535. .setConnectionRequestTimeout(5000)
  536. .setConnectTimeout(3000000)
  537. .setSocketTimeout(3000000)
  538. .build());
  539. httpPost.setHeader("Accept", "application/json");
  540. httpPost.setHeader("Content-Type", "application/json");
  541. String charSet = "UTF-8";
  542. StringEntity entity = new StringEntity(params, charSet);
  543. httpPost.setEntity(entity);
  544. CloseableHttpResponse response = null;
  545. try {
  546. response = httpclient.execute(httpPost);
  547. StatusLine status = response.getStatusLine();
  548. int state = status.getStatusCode();
  549. if (state == HttpStatus.SC_OK) {
  550. HttpEntity responseEntity = response.getEntity();
  551. String jsonString = EntityUtils.toString(responseEntity);
  552. return jsonString;
  553. }
  554. else{
  555. logger.info("请求返回:"+state+"("+url+")");
  556. }
  557. }
  558. catch(Exception e){
  559. logger.error(e.getMessage());
  560. return null;
  561. }
  562. finally {
  563. if (response != null) {
  564. try {
  565. response.close();
  566. } catch (IOException e) {
  567. logger.error(e.getMessage());
  568. }
  569. }
  570. try {
  571. httpclient.close();
  572. } catch (IOException e) {
  573. logger.error(e.getMessage());
  574. }
  575. }
  576. return null;
  577. }
  578. }