HttpUtil.java 29 KB

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