HttpUtil.java 28 KB

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