HttpUtil.java 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  1. package com.uas.eis.utils;
  2. import java.io.BufferedReader;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.InputStreamReader;
  8. import java.io.OutputStream;
  9. import java.io.OutputStreamWriter;
  10. import java.io.UnsupportedEncodingException;
  11. import java.net.HttpURLConnection;
  12. import java.net.URL;
  13. import java.net.URLEncoder;
  14. import java.security.KeyManagementException;
  15. import java.security.NoSuchAlgorithmException;
  16. import java.security.cert.CertificateException;
  17. import java.text.SimpleDateFormat;
  18. import java.util.*;
  19. import java.util.Map.Entry;
  20. import javax.net.ssl.SSLContext;
  21. import javax.net.ssl.TrustManager;
  22. import javax.net.ssl.X509TrustManager;
  23. import com.uas.eis.config.VwmsConfig;
  24. import org.apache.http.Consts;
  25. import org.apache.http.HttpEntity;
  26. import org.apache.http.HttpResponse;
  27. import org.apache.http.NameValuePair;
  28. import org.apache.http.client.ClientProtocolException;
  29. import org.apache.http.client.entity.UrlEncodedFormEntity;
  30. import org.apache.http.client.methods.CloseableHttpResponse;
  31. import org.apache.http.client.methods.HttpDelete;
  32. import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
  33. import org.apache.http.client.methods.HttpGet;
  34. import org.apache.http.client.methods.HttpPost;
  35. import org.apache.http.client.methods.HttpPut;
  36. import org.apache.http.client.methods.HttpRequestBase;
  37. import org.apache.http.config.Registry;
  38. import org.apache.http.config.RegistryBuilder;
  39. import org.apache.http.conn.socket.ConnectionSocketFactory;
  40. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  41. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  42. import org.apache.http.entity.ContentType;
  43. import org.apache.http.entity.StringEntity;
  44. import org.apache.http.entity.mime.MultipartEntityBuilder;
  45. import org.apache.http.entity.mime.content.FileBody;
  46. import org.apache.http.entity.mime.content.InputStreamBody;
  47. import org.apache.http.entity.mime.content.StringBody;
  48. import org.apache.http.impl.client.CloseableHttpClient;
  49. import org.apache.http.impl.client.HttpClients;
  50. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  51. import org.apache.http.message.BasicNameValuePair;
  52. import org.apache.http.protocol.HTTP;
  53. import org.springframework.http.HttpStatus;
  54. import org.springframework.web.bind.annotation.RequestMethod;
  55. import org.springframework.web.multipart.MultipartFile;
  56. /**
  57. * HTTP工具类,封装http请求
  58. *
  59. * @author suntg
  60. * @date 2015年3月5日14:20:40
  61. */
  62. @SuppressWarnings("deprecation")
  63. public class HttpUtil {
  64. /**
  65. * 绕过验证
  66. *
  67. * @return
  68. * @throws NoSuchAlgorithmException
  69. * @throws KeyManagementException
  70. */
  71. public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
  72. SSLContext sc = SSLContext.getInstance("TLSv1.2");
  73. // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
  74. X509TrustManager trustManager = new X509TrustManager() {
  75. @Override
  76. public void checkClientTrusted(
  77. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  78. String paramString) throws CertificateException {
  79. }
  80. @Override
  81. public void checkServerTrusted(
  82. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  83. String paramString) throws CertificateException {
  84. }
  85. @Override
  86. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  87. return null;
  88. }
  89. };
  90. sc.init(null, new TrustManager[] { trustManager }, null);
  91. return sc;
  92. }
  93. /**
  94. * 发送GET请求
  95. *
  96. * @param url
  97. * @param params
  98. * @return
  99. * @throws Exception
  100. */
  101. public static Response sendGetRequest(String url, HashMap<String, String> header, Map<String, String> params) throws Exception {
  102. return sendGetRequest(url, header, params, false, null);
  103. }
  104. /**
  105. * 发送GET请求
  106. *
  107. * @param url
  108. * @param params
  109. * @param sign
  110. * 是否发送签名
  111. * @return
  112. * @throws Exception
  113. */
  114. public static Response sendGetRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign, String signKey) throws Exception {
  115. return sendRequest(RequestMethod.GET, url, header, params, sign, signKey);
  116. }
  117. /**
  118. * 发送GET请求
  119. *
  120. * @param url
  121. * @param params
  122. * @param sign
  123. * 是否发送签名
  124. * @return
  125. * @throws Exception
  126. */
  127. public static Response sendGetRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign) throws Exception {
  128. return sendRequest(RequestMethod.GET, url, header, params, sign, null);
  129. }
  130. /**
  131. * 发送POST请求
  132. *
  133. * @param url
  134. * @param params
  135. * @return
  136. * @throws Exception
  137. */
  138. public static Response sendPostRequest(String url, HashMap<String, String> header, Map<String, String> params) throws Exception {
  139. return sendPostRequest(url, header, params, false, null);
  140. }
  141. /**
  142. * 发送POST请求
  143. *
  144. * @param url
  145. * @param params
  146. * @return
  147. * @throws Exception
  148. */
  149. public static Response sendPostRequest(String url, List<?> datas) throws Exception {
  150. return sendPostRequest(url, datas, false, null);
  151. }
  152. /**
  153. * 发送POST请求
  154. *
  155. * @param url
  156. * @param params
  157. * @param sign
  158. * 是否发送签名
  159. * @return
  160. * @throws Exception
  161. */
  162. public static Response sendPostRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign, String signKey) throws Exception {
  163. return sendRequest(RequestMethod.POST, url, header, params, sign, signKey);
  164. }
  165. /**
  166. * 发送POST请求
  167. *
  168. * @param url
  169. * @param datas
  170. * @param sign
  171. * 是否发送签名
  172. * @return
  173. * @throws Exception
  174. */
  175. public static Response sendPostRequest(String url, List<?> datas, boolean sign, String signKey) throws Exception {
  176. return sendRequest(RequestMethod.POST, url, datas, sign, signKey);
  177. }
  178. /**
  179. * 发送POST请求
  180. *
  181. * <pre>
  182. * 使用默认密钥
  183. * </pre>
  184. *
  185. * @param url
  186. * @param params
  187. * @param sign
  188. * 是否发送签名
  189. * @return
  190. * @throws Exception
  191. */
  192. public static Response sendPostRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign) throws Exception {
  193. return sendRequest(RequestMethod.POST, url, header, params, sign, null);
  194. }
  195. public static Response sendPostRequest(String url, HashMap<String, String> header, String body) throws Exception {
  196. return sendRequest(RequestMethod.POST, url, header, body, false, null);
  197. }
  198. /**
  199. * 发送POST请求
  200. *
  201. * <pre>
  202. * 使用默认密钥
  203. * </pre>
  204. *
  205. * @param url
  206. * @param params
  207. * @param sign
  208. * 是否发送签名
  209. * @return
  210. * @throws Exception
  211. */
  212. public static Response sendPostRequest(String url, List<?> datas, boolean sign) throws Exception {
  213. return sendRequest(RequestMethod.POST, url, datas, sign, null);
  214. }
  215. /**
  216. * 发送post请求
  217. *
  218. * @param postUrl
  219. * @param formData
  220. * @return
  221. * @throws Exception
  222. */
  223. public static Response doPost(String postUrl, String formData, boolean sign, String signKey) throws Exception {
  224. CloseableHttpClient httpClient = HttpClients.createDefault();
  225. postUrl = getUrl(postUrl, sign, signKey);
  226. HttpPost post = new HttpPost(postUrl);
  227. StringEntity postingString = new StringEntity(formData, HTTP.UTF_8);
  228. post.setEntity(postingString);
  229. post.setHeader("Content-type", "application/json");
  230. CloseableHttpResponse response = httpClient.execute(post);
  231. return Response.getResponse(response);
  232. }
  233. public static Response doPost(String postUrl, String formData, boolean sign, String signKey, int timeout) throws Exception {
  234. URL url = new URL(postUrl);
  235. HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
  236. try {
  237. urlConn.setDoOutput(true);
  238. urlConn.setDoInput(true);
  239. urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  240. urlConn.setUseCaches(false);
  241. urlConn.setInstanceFollowRedirects(true);
  242. urlConn.setRequestMethod("POST");
  243. urlConn.setConnectTimeout(timeout);
  244. urlConn.setReadTimeout(timeout);
  245. if (null != formData) {
  246. OutputStreamWriter osw = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
  247. osw.write(formData);
  248. osw.flush();
  249. osw.close();
  250. }
  251. return new Response(urlConn.getResponseCode() == 200, streamToString(urlConn.getInputStream()));
  252. } catch (Exception e) {
  253. return new Response(false, e.getMessage());
  254. } finally {
  255. if (urlConn != null) {
  256. urlConn.disconnect();
  257. }
  258. }
  259. }
  260. public static String streamToString(InputStream in) throws Exception {
  261. BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  262. StringBuilder buf = new StringBuilder();
  263. try {
  264. char[] chars = new char[2048];
  265. for (;;) {
  266. int len = reader.read(chars, 0, chars.length);
  267. if (len < 0) {
  268. break;
  269. }
  270. buf.append(chars, 0, len);
  271. }
  272. } catch (Exception ex) {
  273. throw new Exception("read string from reader error", ex);
  274. }
  275. return buf.toString();
  276. }
  277. /**
  278. * 封装加密
  279. *
  280. * @param postUrl
  281. * @param sign
  282. * @param signKey
  283. * @return
  284. */
  285. private static String getUrl(String url, boolean sign, String signKey) {
  286. StringBuilder buf = new StringBuilder(url);
  287. if (sign) {
  288. // 加时间戳,保持相同请求每次签名均不一样
  289. buf.append("&_timestamp=").append(System.currentTimeMillis());
  290. String message = buf.toString();
  291. // 对请求串进行签名
  292. buf.append("&_signature=").append(HmacUtils.encode(message, signKey));
  293. } else
  294. buf.deleteCharAt(buf.length() - 1);
  295. return buf.toString();
  296. }
  297. /**
  298. * 发送PUT请求
  299. *
  300. * <pre>
  301. * 使用默认密钥
  302. * </pre>
  303. *
  304. * @param url
  305. * @param params
  306. * @param sign
  307. * 是否发送签名
  308. * @return
  309. * @throws Exception
  310. */
  311. public static Response sendPutRequest(String url, List<?> datas, boolean sign) throws Exception {
  312. return sendRequest(RequestMethod.PUT, url, datas, sign, null);
  313. }
  314. /**
  315. * 发送PUT请求
  316. *
  317. * <pre>
  318. * 使用默认密钥
  319. * </pre>
  320. *
  321. * @param url
  322. * @param params
  323. * @param sign
  324. * 是否发送签名
  325. * @return
  326. * @throws Exception
  327. */
  328. public static Response sendPutRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign) throws Exception {
  329. return sendRequest(RequestMethod.PUT, url, header, params, sign, null);
  330. }
  331. /**
  332. * 发送PUT请求
  333. *
  334. * @param url
  335. * @param datas
  336. * @param sign
  337. * 是否发送签名
  338. * @return
  339. * @throws Exception
  340. */
  341. public static Response sendPutRequest(String url, List<?> datas, boolean sign, String signKey) throws Exception {
  342. return sendRequest(RequestMethod.PUT, url, datas, sign, signKey);
  343. }
  344. /**
  345. * 发送PUT请求
  346. *
  347. * @param url
  348. * @param params
  349. * @return
  350. * @throws Exception
  351. */
  352. public static Response sendPutRequest(String url, List<?> datas) throws Exception {
  353. return sendPutRequest(url, datas, false, null);
  354. }
  355. /**
  356. * 发送DELETE请求
  357. *
  358. * @param url
  359. * @param params
  360. *
  361. * @return
  362. * @throws Exception
  363. */
  364. public static Response sendDeleteRequest(String url, HashMap<String, String> header, Map<String, String> params) throws Exception {
  365. return sendDeleteRequest(url, header, params, false, null);
  366. }
  367. /**
  368. * 发送DELETE请求
  369. *
  370. * @param url
  371. * @param params
  372. * @param sign
  373. * 是否发送签名
  374. * @return
  375. * @throws Exception
  376. */
  377. public static Response sendDeleteRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign, String signKey) throws Exception {
  378. return sendRequest(RequestMethod.DELETE, url, header, params, sign, signKey);
  379. }
  380. /**
  381. * 发送DELETE请求
  382. *
  383. * @param url
  384. * @param params
  385. * @param sign
  386. * 是否发送签名
  387. * @return
  388. * @throws Exception
  389. */
  390. public static Response sendDeleteRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign) throws Exception {
  391. return sendRequest(RequestMethod.DELETE, url, header, params, sign, null);
  392. }
  393. /**
  394. * 发起http请求
  395. *
  396. * @param method
  397. * 请求方法GET、POST、PUT、DELETE
  398. * @param url
  399. * 请求链接
  400. * @param params
  401. * 参数
  402. *
  403. * @param sign
  404. * 是否签名
  405. * @return
  406. * @throws Exception
  407. */
  408. public static Response sendRequest(RequestMethod method, String url, HashMap<String, String> header, Map<String, String> params, boolean sign, String signKey)
  409. throws Exception {
  410. switch (method) {
  411. case GET: {
  412. HttpRequestBase request = new HttpGet(getRequestUrl(url, params, sign, signKey));
  413. for (Map.Entry<String, String> entry : header.entrySet()) {
  414. request.setHeader(entry.getKey(), entry.getValue());
  415. }
  416. return sendHttpUriRequest(request);
  417. }
  418. case POST: {
  419. HttpPost request = new HttpPost(getRequestUrl(url, sign, signKey));
  420. for (Map.Entry<String, String> entry : header.entrySet()) {
  421. request.setHeader(entry.getKey(), entry.getValue());
  422. }
  423. return sendHttpEntityEnclosingRequest(request, params);
  424. }
  425. case PUT: {
  426. HttpPut request = new HttpPut(getRequestUrl(url, sign, signKey));
  427. for (Map.Entry<String, String> entry : header.entrySet()) {
  428. request.setHeader(entry.getKey(), entry.getValue());
  429. }
  430. return sendHttpEntityEnclosingRequest(request, params);
  431. }
  432. case DELETE: {
  433. HttpDelete request = new HttpDelete(getRequestUrl(url, params, sign, signKey));
  434. for (Map.Entry<String, String> entry : header.entrySet()) {
  435. request.setHeader(entry.getKey(), entry.getValue());
  436. }
  437. return sendHttpUriRequest(request);
  438. }
  439. default: {
  440. HttpGet request = new HttpGet(getRequestUrl(url, params, sign, signKey));
  441. for (Map.Entry<String, String> entry : header.entrySet()) {
  442. request.setHeader(entry.getKey(), entry.getValue());
  443. }
  444. return sendHttpUriRequest(request);
  445. }
  446. }
  447. }
  448. public static Response sendRequest(RequestMethod method, String url, HashMap<String, String> header, String body, boolean sign, String signKey)
  449. throws Exception {
  450. HttpPost request = new HttpPost(getRequestUrl(url, sign, signKey));
  451. for (Map.Entry<String, String> entry : header.entrySet()) {
  452. request.setHeader(entry.getKey(), entry.getValue());
  453. }
  454. //采用绕过验证的方式处理https请求
  455. SSLContext sslcontext = createIgnoreVerifySSL();
  456. // 设置协议http和https对应的处理socket链接工厂的对象
  457. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  458. .register("http", PlainConnectionSocketFactory.INSTANCE)
  459. .register("https", new SSLConnectionSocketFactory(sslcontext))
  460. .build();
  461. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  462. HttpClients.custom().setConnectionManager(connManager);
  463. //创建自定义的httpclient对象
  464. CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
  465. CloseableHttpResponse response = null;
  466. try {
  467. request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  468. request.setEntity(new StringEntity(body,"UTF-8"));
  469. response = httpClient.execute(request);
  470. return Response.getResponse(response);
  471. } finally {
  472. request.releaseConnection();
  473. try {
  474. httpClient.close();
  475. } catch (IOException e) {
  476. }
  477. if (response != null) {
  478. try {
  479. response.close();
  480. } catch (IOException e) {
  481. }
  482. }
  483. }
  484. }
  485. /**
  486. * 发起http请求
  487. *
  488. * @param method
  489. * 请求方法POST、PUT
  490. * @param url
  491. * 请求链接
  492. * @param datas
  493. * 参数
  494. * @param sign
  495. * 是否签名
  496. * @return
  497. * @throws Exception
  498. */
  499. public static Response sendRequest(RequestMethod method, String url, List<?> datas, boolean sign, String signKey) throws Exception {
  500. switch (method) {
  501. case POST:
  502. return sendHttpEntityEnclosingRequest(new HttpPost(getRequestUrl(url, sign, signKey)), datas);
  503. case PUT:
  504. return sendHttpEntityEnclosingRequest(new HttpPut(getRequestUrl(url, sign, signKey)), datas);
  505. default:
  506. return sendHttpEntityEnclosingRequest(new HttpPost(getRequestUrl(url, sign, signKey)), datas);
  507. }
  508. }
  509. /**
  510. * 发起GET、DELETE请求
  511. *
  512. * @param request
  513. * @return
  514. * @throws Exception
  515. */
  516. private static Response sendHttpUriRequest(HttpRequestBase request) throws Exception {
  517. //采用绕过验证的方式处理https请求
  518. SSLContext sslcontext = createIgnoreVerifySSL();
  519. // 设置协议http和https对应的处理socket链接工厂的对象
  520. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  521. .register("http", PlainConnectionSocketFactory.INSTANCE)
  522. .register("https", new SSLConnectionSocketFactory(sslcontext))
  523. .build();
  524. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  525. HttpClients.custom().setConnectionManager(connManager);
  526. //创建自定义的httpclient对象
  527. CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
  528. //CloseableHttpClient httpClient = HttpClients.createDefault();
  529. CloseableHttpResponse response = null;
  530. try {
  531. response = httpClient.execute(request);
  532. return Response.getResponse(response);
  533. } finally {
  534. try {
  535. httpClient.close();
  536. } catch (IOException e) {
  537. }
  538. if (response != null) {
  539. try {
  540. response.close();
  541. } catch (IOException e) {
  542. }
  543. }
  544. }
  545. }
  546. /**
  547. * 发起POST、PUT请求
  548. *
  549. * @param request
  550. * @param params
  551. * @return
  552. * @throws Exception
  553. */
  554. private static Response sendHttpEntityEnclosingRequest(HttpEntityEnclosingRequestBase request, Map<String, String> params)
  555. throws Exception {
  556. //采用绕过验证的方式处理https请求
  557. SSLContext sslcontext = createIgnoreVerifySSL();
  558. // 设置协议http和https对应的处理socket链接工厂的对象
  559. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  560. .register("http", PlainConnectionSocketFactory.INSTANCE)
  561. .register("https", new SSLConnectionSocketFactory(sslcontext))
  562. .build();
  563. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  564. HttpClients.custom().setConnectionManager(connManager);
  565. //创建自定义的httpclient对象
  566. CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
  567. //CloseableHttpClient httpClient = HttpClients.createDefault();
  568. CloseableHttpResponse response = null;
  569. try {
  570. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  571. if (params != null && !params.isEmpty()) {
  572. Set<Entry<String, String>> entrys = params.entrySet();
  573. for (Map.Entry<String, String> entry : entrys) {
  574. nvps.add(new BasicNameValuePair(entry.getKey(), URLEncoder.encode(entry.getValue(), "UTF-8")));
  575. }
  576. }
  577. request.setEntity(new UrlEncodedFormEntity(nvps));
  578. response = httpClient.execute(request);
  579. return Response.getResponse(response);
  580. } finally {
  581. request.releaseConnection();
  582. try {
  583. httpClient.close();
  584. } catch (IOException e) {
  585. }
  586. if (response != null) {
  587. try {
  588. response.close();
  589. } catch (IOException e) {
  590. }
  591. }
  592. }
  593. }
  594. /**
  595. * 发起POST、PUT请求
  596. *
  597. * @param request
  598. * @param datas
  599. * @return
  600. * @throws Exception
  601. */
  602. private static Response sendHttpEntityEnclosingRequest(HttpEntityEnclosingRequestBase request, List<?> datas) throws Exception {
  603. //采用绕过验证的方式处理https请求
  604. SSLContext sslcontext = createIgnoreVerifySSL();
  605. // 设置协议http和https对应的处理socket链接工厂的对象
  606. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  607. .register("http", PlainConnectionSocketFactory.INSTANCE)
  608. .register("https", new SSLConnectionSocketFactory(sslcontext))
  609. .build();
  610. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  611. HttpClients.custom().setConnectionManager(connManager);
  612. //创建自定义的httpclient对象
  613. CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
  614. //CloseableHttpClient httpClient = HttpClients.createDefault();
  615. CloseableHttpResponse response = null;
  616. try {
  617. if (datas != null && !datas.isEmpty()) {
  618. request.setEntity(new StringEntity(FlexJsonUtil.toJsonArrayDeep(datas), ContentType.create("text/plain", Consts.UTF_8)));
  619. }
  620. response = httpClient.execute(request);
  621. return Response.getResponse(response);
  622. } finally {
  623. request.releaseConnection();
  624. try {
  625. httpClient.close();
  626. } catch (IOException e) {
  627. }
  628. if (response != null) {
  629. try {
  630. response.close();
  631. } catch (IOException e) {
  632. }
  633. }
  634. }
  635. }
  636. /**
  637. * 将请求参数添加到链接中
  638. *
  639. * @param url
  640. * @param params
  641. * @param sign
  642. * 是否签名
  643. * @return
  644. * @throws UnsupportedEncodingException
  645. */
  646. public static String getRequestUrl(String url, Map<String, String> params, boolean sign) throws UnsupportedEncodingException {
  647. StringBuilder buf = new StringBuilder(url);
  648. if (url.indexOf("?") == -1)
  649. buf.append("?");
  650. else if (!url.endsWith("&"))
  651. buf.append("&");
  652. // 如果是GET请求,则请求参数在URL中
  653. if (params != null && !params.isEmpty()) {
  654. Set<Entry<String, String>> entrys = params.entrySet();
  655. for (Map.Entry<String, String> entry : entrys) {
  656. buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&");
  657. }
  658. }
  659. if (sign) {
  660. // 加时间戳,保持相同请求每次签名均不一样
  661. buf.append("_timestamp=").append(System.currentTimeMillis());
  662. String message = buf.toString();
  663. // 对请求串进行签名
  664. buf.append("&_signature=").append(HmacUtils.encode(message));
  665. } else
  666. buf.deleteCharAt(buf.length() - 1);
  667. return buf.toString();
  668. }
  669. /**
  670. * 将请求参数添加到链接中
  671. *
  672. * @param url
  673. * @param params
  674. * @param sign
  675. * 是否签名
  676. * @param signKey
  677. * 签名密钥
  678. * @return
  679. * @throws UnsupportedEncodingException
  680. */
  681. public static String getRequestUrl(String url, Map<String, String> params, boolean sign, String signKey)
  682. throws UnsupportedEncodingException {
  683. if (sign && signKey == null)
  684. return getRequestUrl(url, params, sign);
  685. StringBuilder buf = new StringBuilder(url);
  686. if (url.indexOf("?") == -1)
  687. buf.append("?");
  688. else if (!url.endsWith("&"))
  689. buf.append("&");
  690. // 如果是GET请求,则请求参数在URL中
  691. if (params != null && !params.isEmpty()) {
  692. Set<Entry<String, String>> entrys = params.entrySet();
  693. for (Map.Entry<String, String> entry : entrys) {
  694. buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&");
  695. }
  696. }
  697. if (sign) {
  698. // 加时间戳,保持相同请求每次签名均不一样
  699. buf.append("_timestamp=").append(System.currentTimeMillis());
  700. String message = buf.toString();
  701. // 对请求串进行签名
  702. buf.append("&_signature=").append(HmacUtils.encode(message, signKey));
  703. } else
  704. buf.deleteCharAt(buf.length() - 1);
  705. return buf.toString();
  706. }
  707. /**
  708. * 将签名信息添加到链接中
  709. *
  710. * @param url
  711. * @param sign
  712. * 是否签名
  713. * @return
  714. * @throws UnsupportedEncodingException
  715. */
  716. private static String getRequestUrl(String url, boolean sign, String signKey) throws UnsupportedEncodingException {
  717. return getRequestUrl(url, null, sign, signKey);
  718. }
  719. /**
  720. * 将输入流转为字节数组
  721. *
  722. * @param inStream
  723. * @return
  724. * @throws Exception
  725. */
  726. public static byte[] read2Byte(InputStream inStream) throws Exception {
  727. ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
  728. byte[] buffer = new byte[1024];
  729. int len = 0;
  730. while ((len = inStream.read(buffer)) != -1) {
  731. outSteam.write(buffer, 0, len);
  732. }
  733. outSteam.close();
  734. inStream.close();
  735. return outSteam.toByteArray();
  736. }
  737. /**
  738. * 将输入流转为字符串
  739. *
  740. * @param inStream
  741. * @return
  742. * @throws Exception
  743. */
  744. public static String read2String(InputStream inStream) throws Exception {
  745. ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
  746. byte[] buffer = new byte[1024];
  747. int len = 0;
  748. while ((len = inStream.read(buffer)) != -1) {
  749. outSteam.write(buffer, 0, len);
  750. }
  751. try {
  752. outSteam.close();
  753. inStream.close();
  754. } catch (Exception e) {
  755. }
  756. return new String(outSteam.toByteArray(), "UTF-8");
  757. }
  758. /**
  759. * 发送xml数据
  760. *
  761. * @param path
  762. * 请求地址
  763. * @param xml
  764. * xml数据
  765. * @param encoding
  766. * 编码
  767. * @return
  768. * @throws Exception
  769. */
  770. public static byte[] postXml(String path, String xml, String encoding) throws Exception {
  771. byte[] data = xml.getBytes(encoding);
  772. URL url = new URL(path);
  773. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  774. conn.setRequestMethod("POST");
  775. conn.setDoOutput(true);
  776. conn.setRequestProperty("Content-Type", "text/xml; charset=" + encoding);
  777. conn.setRequestProperty("Content-Length", String.valueOf(data.length));
  778. conn.setConnectTimeout(5 * 1000);
  779. OutputStream outStream = conn.getOutputStream();
  780. outStream.write(data);
  781. outStream.flush();
  782. outStream.close();
  783. if (conn.getResponseCode() == HttpStatus.OK.value()) {
  784. return read2Byte(conn.getInputStream());
  785. }
  786. return null;
  787. }
  788. /**
  789. * http上传文件
  790. *
  791. * @param postUrl
  792. * 请求地址
  793. * @param filePath
  794. * 附件路径
  795. * @param params
  796. * 参数
  797. * @return
  798. * @throws Exception
  799. * @throws IOException
  800. * @throws IllegalStateException
  801. */
  802. public static Response upload(String postUrl, String filePath, Map<String, String> params, boolean sign, String signKey)
  803. throws IllegalStateException, IOException, Exception {
  804. CloseableHttpClient httpClient = null;
  805. CloseableHttpResponse response = null;
  806. try {
  807. httpClient = HttpClients.createDefault();
  808. HttpPost httpPost = new HttpPost(getRequestUrl(postUrl, sign, signKey));
  809. FileBody fileBody = new FileBody(new File(filePath));
  810. MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  811. builder.addPart("file", fileBody);
  812. if (params != null) {
  813. for (String paramKey : params.keySet()) {
  814. StringBody body = new StringBody(params.get(paramKey), ContentType.create("text/plain", Consts.UTF_8));
  815. builder.addPart(paramKey, body);
  816. }
  817. }
  818. HttpEntity reqEntity = builder.build();
  819. httpPost.setEntity(reqEntity);
  820. response = httpClient.execute(httpPost);
  821. } finally {
  822. try {
  823. if (response != null) {
  824. response.close();
  825. }
  826. } catch (IOException e) {
  827. e.printStackTrace();
  828. }
  829. try {
  830. if (httpClient != null) {
  831. httpClient.close();
  832. }
  833. } catch (IOException e) {
  834. e.printStackTrace();
  835. }
  836. }
  837. return Response.getResponse(response);
  838. }
  839. /**
  840. * http上传文件
  841. *
  842. * @param postUrl
  843. * 请求地址
  844. * @param file
  845. * 附件
  846. * @param params
  847. * 参数
  848. * @return
  849. * @throws Exception
  850. * @throws IOException
  851. * @throws IllegalStateException
  852. */
  853. public static Response upload(String postUrl, MultipartFile file, Map<String, String> params, boolean sign, String signKey)
  854. throws IllegalStateException, IOException, Exception {
  855. CloseableHttpClient httpClient = null;
  856. CloseableHttpResponse response = null;
  857. try {
  858. httpClient = HttpClients.createDefault();
  859. HttpPost httpPost = new HttpPost(getRequestUrl(postUrl, sign, signKey));
  860. InputStreamBody sbody = new InputStreamBody(file.getInputStream(), file.getOriginalFilename());
  861. MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  862. builder.addPart("file", sbody);
  863. if (params != null) {
  864. for (String paramKey : params.keySet()) {
  865. StringBody body = new StringBody(params.get(paramKey), ContentType.create("text/plain", Consts.UTF_8));
  866. builder.addPart(paramKey, body);
  867. }
  868. }
  869. HttpEntity reqEntity = builder.build();
  870. httpPost.setEntity(reqEntity);
  871. response = httpClient.execute(httpPost);
  872. } finally {
  873. try {
  874. if (response != null) {
  875. response.close();
  876. }
  877. } catch (IOException e) {
  878. e.printStackTrace();
  879. }
  880. try {
  881. if (httpClient != null) {
  882. httpClient.close();
  883. }
  884. } catch (IOException e) {
  885. e.printStackTrace();
  886. }
  887. }
  888. return Response.getResponse(response);
  889. }
  890. /**
  891. * 下载
  892. *
  893. * @param postUrl
  894. * @return
  895. * @throws ClientProtocolException
  896. * @throws IOException
  897. * @throws NoSuchAlgorithmException
  898. * @throws KeyManagementException
  899. */
  900. public static InputStream download(String postUrl) throws ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException {
  901. //采用绕过验证的方式处理https请求
  902. SSLContext sslcontext = createIgnoreVerifySSL();
  903. // 设置协议http和https对应的处理socket链接工厂的对象
  904. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  905. .register("http", PlainConnectionSocketFactory.INSTANCE)
  906. .register("https", new SSLConnectionSocketFactory(sslcontext))
  907. .build();
  908. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  909. HttpClients.custom().setConnectionManager(connManager);
  910. //创建自定义的httpclient对象
  911. CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
  912. //CloseableHttpClient httpClient = HttpClients.createDefault();
  913. HttpGet httpGet = new HttpGet(postUrl);
  914. CloseableHttpResponse response = httpClient.execute(httpGet);
  915. return response.getEntity().getContent();
  916. }
  917. public static Response doPostToVWMS(String method,String formData, VwmsConfig vwmsConfig) throws Exception {
  918. CloseableHttpClient httpClient = HttpClients.createDefault();
  919. String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
  920. //"{secretkey}app_key{app_key}customerId{customerId}formatjsonmethod{openapi_name}sign_methodmd5timestamp2015-04-26 00:00:07v2.0{body}{secretkey}";
  921. String signMsg= String.format("%sapp_key%scustomerId%sformatjsonmethod%ssign_methodmd5timestamp%sv2.0%s%s",
  922. vwmsConfig.getAppSecret(),vwmsConfig.getAppKey(), vwmsConfig.getCustomerId(),method,timestamp,formData,vwmsConfig.getAppSecret() );
  923. //http://{openapiUrl}?method=openapi.singleitem.synchronize&timestamp=2015-04-26%2000:00:07&format=json&app_key={app_key}&v=2.0&sign=D06D88CB34B2EC0E5C9BAB396C9542B6&sign_method=md5&customerId={customerId}
  924. StringBuilder postUrl = new StringBuilder(vwmsConfig.getApiUrl());
  925. postUrl.append("?method=").append(method)
  926. .append("&timestamp=").append(System.currentTimeMillis()).append("&format=json").append("&app_key=").append(vwmsConfig.getAppKey())
  927. .append("&v=2.0")
  928. .append("&_signature=").append(HmacUtils.encode(signMsg, vwmsConfig.getAppSecret())) // 对请求串进行签名
  929. .append("&sign_method=md5").append("&customerId=").append(vwmsConfig.getCustomerId());
  930. // System.out.println("postUrl:"+postUrl.toString());
  931. // System.out.println("postingString:"+formData.toString());
  932. // postUrl = new StringBuilder();
  933. HttpPost post = new HttpPost(postUrl.toString());
  934. StringEntity postingString = new StringEntity(formData, HTTP.UTF_8);
  935. post.setEntity(postingString);
  936. post.setHeader("Content-type", "application/json");
  937. CloseableHttpResponse response = httpClient.execute(post);
  938. return Response.getResponse(response);
  939. }
  940. public static byte[] postXmlToVWMS(String method, String xml, String encoding,VwmsConfig vwmsConfig) throws Exception {
  941. byte[] data = xml.getBytes(encoding);
  942. String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
  943. //"{secretkey}app_key{app_key}customerId{customerId}formatjsonmethod{openapi_name}sign_methodmd5timestamp2015-04-26 00:00:07v2.0{body}{secretkey}";
  944. String signMsg= String.format("%sapp_key%scustomerId%sformatjsonmethod%ssign_methodmd5timestamp%sv2.0%s%s",
  945. vwmsConfig.getAppSecret(),vwmsConfig.getAppKey(), vwmsConfig.getCustomerId(),method,timestamp,xml,vwmsConfig.getAppSecret() );
  946. StringBuilder postUrl = new StringBuilder(vwmsConfig.getApiUrl());
  947. postUrl.append("?method=").append(method)
  948. .append("&timestamp=").append(System.currentTimeMillis()).append("&format=xml").append("&app_key=").append(vwmsConfig.getAppKey())
  949. .append("&v=2.0")
  950. .append("&_signature=").append(HmacUtils.encode(signMsg, vwmsConfig.getAppSecret())) // 对请求串进行签名
  951. .append("&sign_method=md5").append("&customerId=").append(vwmsConfig.getCustomerId());
  952. URL url = new URL(postUrl.toString());
  953. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  954. conn.setRequestMethod("POST");
  955. conn.setDoOutput(true);
  956. conn.setRequestProperty("Content-Type", "text/xml; charset=" + encoding);
  957. conn.setRequestProperty("Content-Length", String.valueOf(data.length));
  958. conn.setConnectTimeout(5 * 1000);
  959. OutputStream outStream = conn.getOutputStream();
  960. outStream.write(data);
  961. outStream.flush();
  962. outStream.close();
  963. if (conn.getResponseCode() == HttpStatus.OK.value()||conn.getResponseCode() == HttpStatus.CREATED.value()) {
  964. return read2Byte(conn.getInputStream());
  965. }
  966. return null;
  967. }
  968. public static class Response {
  969. private int statusCode;
  970. private String responseText;
  971. public int getStatusCode() {
  972. return statusCode;
  973. }
  974. public void setStatusCode(int statusCode) {
  975. this.statusCode = statusCode;
  976. }
  977. public String getResponseText() {
  978. return responseText;
  979. }
  980. public void setResponseText(String responseText) {
  981. this.responseText = responseText;
  982. }
  983. public Response() {
  984. }
  985. public Response(boolean success, String content) {
  986. super();
  987. this.statusCode = success ? 200 : 404;
  988. this.responseText = content;
  989. }
  990. public Response(HttpResponse response) throws IllegalStateException, IOException, Exception {
  991. this.statusCode = response.getStatusLine().getStatusCode();
  992. this.responseText = HttpUtil.read2String(response.getEntity().getContent());
  993. }
  994. public static Response getResponse(HttpResponse response) throws IllegalStateException, IOException, Exception {
  995. if (response != null)
  996. return new Response(response);
  997. return null;
  998. }
  999. }
  1000. }