HttpUtil.java 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  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.HttpEntity;
  29. import org.apache.http.HttpResponse;
  30. import org.apache.http.NameValuePair;
  31. import org.apache.http.client.ClientProtocolException;
  32. import org.apache.http.client.entity.UrlEncodedFormEntity;
  33. import org.apache.http.client.methods.CloseableHttpResponse;
  34. import org.apache.http.client.methods.HttpDelete;
  35. import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
  36. import org.apache.http.client.methods.HttpGet;
  37. import org.apache.http.client.methods.HttpPost;
  38. import org.apache.http.client.methods.HttpPut;
  39. import org.apache.http.client.methods.HttpRequestBase;
  40. import org.apache.http.config.Registry;
  41. import org.apache.http.config.RegistryBuilder;
  42. import org.apache.http.conn.socket.ConnectionSocketFactory;
  43. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  44. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  45. import org.apache.http.entity.ContentType;
  46. import org.apache.http.entity.StringEntity;
  47. import org.apache.http.entity.mime.MultipartEntityBuilder;
  48. import org.apache.http.entity.mime.content.FileBody;
  49. import org.apache.http.entity.mime.content.InputStreamBody;
  50. import org.apache.http.entity.mime.content.StringBody;
  51. import org.apache.http.impl.client.CloseableHttpClient;
  52. import org.apache.http.impl.client.HttpClients;
  53. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  54. import org.apache.http.message.BasicNameValuePair;
  55. import org.apache.http.protocol.HTTP;
  56. import org.springframework.http.HttpStatus;
  57. import org.springframework.web.bind.annotation.RequestMethod;
  58. import org.springframework.web.multipart.MultipartFile;
  59. /**
  60. * HTTP工具类,封装http请求
  61. *
  62. * @author suntg
  63. * @date 2015年3月5日14:20:40
  64. */
  65. @SuppressWarnings("deprecation")
  66. public class HttpUtil {
  67. /**
  68. * 绕过验证
  69. *
  70. * @return
  71. * @throws NoSuchAlgorithmException
  72. * @throws KeyManagementException
  73. */
  74. public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
  75. SSLContext sc = SSLContext.getInstance("SSLv3");
  76. // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
  77. X509TrustManager trustManager = new X509TrustManager() {
  78. @Override
  79. public void checkClientTrusted(
  80. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  81. String paramString) throws CertificateException {
  82. }
  83. @Override
  84. public void checkServerTrusted(
  85. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  86. String paramString) throws CertificateException {
  87. }
  88. @Override
  89. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  90. return null;
  91. }
  92. };
  93. sc.init(null, new TrustManager[] { trustManager }, null);
  94. return sc;
  95. }
  96. /**
  97. * 发送GET请求
  98. *
  99. * @param url
  100. * @param params
  101. * @return
  102. * @throws Exception
  103. */
  104. public static Response sendGetRequest(String url, HashMap<String, String> header, Map<String, String> params) throws Exception {
  105. return sendGetRequest(url, header, params, false, null);
  106. }
  107. /**
  108. * 发送GET请求
  109. *
  110. * @param url
  111. * @param params
  112. * @param sign
  113. * 是否发送签名
  114. * @return
  115. * @throws Exception
  116. */
  117. public static Response sendGetRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign, String signKey) throws Exception {
  118. return sendRequest(RequestMethod.GET, url, header, params, sign, signKey);
  119. }
  120. /**
  121. * 发送GET请求
  122. *
  123. * @param url
  124. * @param params
  125. * @param sign
  126. * 是否发送签名
  127. * @return
  128. * @throws Exception
  129. */
  130. public static Response sendGetRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign) throws Exception {
  131. return sendRequest(RequestMethod.GET, url, header, params, sign, null);
  132. }
  133. /**
  134. * 发送POST请求
  135. *
  136. * @param url
  137. * @param params
  138. * @return
  139. * @throws Exception
  140. */
  141. public static Response sendPostRequest(String url, HashMap<String, String> header, Map<String, String> params) throws Exception {
  142. return sendPostRequest(url, header, params, false, null);
  143. }
  144. /**
  145. * 发送POST请求
  146. *
  147. * @param url
  148. * @param params
  149. * @return
  150. * @throws Exception
  151. */
  152. public static Response sendPostRequest(String url, List<?> datas) throws Exception {
  153. return sendPostRequest(url, datas, false, null);
  154. }
  155. /**
  156. * 发送POST请求
  157. *
  158. * @param url
  159. * @param params
  160. * @param sign
  161. * 是否发送签名
  162. * @return
  163. * @throws Exception
  164. */
  165. public static Response sendPostRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign, String signKey) throws Exception {
  166. return sendRequest(RequestMethod.POST, url, header, params, sign, signKey);
  167. }
  168. /**
  169. * 发送POST请求
  170. *
  171. * @param url
  172. * @param datas
  173. * @param sign
  174. * 是否发送签名
  175. * @return
  176. * @throws Exception
  177. */
  178. public static Response sendPostRequest(String url, List<?> datas, boolean sign, String signKey) throws Exception {
  179. return sendRequest(RequestMethod.POST, url, datas, sign, signKey);
  180. }
  181. /**
  182. * 发送POST请求
  183. *
  184. * <pre>
  185. * 使用默认密钥
  186. * </pre>
  187. *
  188. * @param url
  189. * @param params
  190. * @param sign
  191. * 是否发送签名
  192. * @return
  193. * @throws Exception
  194. */
  195. public static Response sendPostRequest(String url, HashMap<String, String> header, Map<String, String> params, boolean sign) throws Exception {
  196. return sendRequest(RequestMethod.POST, url, header, params, sign, 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. /**
  449. * 发起http请求
  450. *
  451. * @param method
  452. * 请求方法POST、PUT
  453. * @param url
  454. * 请求链接
  455. * @param datas
  456. * 参数
  457. * @param sign
  458. * 是否签名
  459. * @return
  460. * @throws Exception
  461. */
  462. public static Response sendRequest(RequestMethod method, String url, List<?> datas, boolean sign, String signKey) throws Exception {
  463. switch (method) {
  464. case POST:
  465. return sendHttpEntityEnclosingRequest(new HttpPost(getRequestUrl(url, sign, signKey)), datas);
  466. case PUT:
  467. return sendHttpEntityEnclosingRequest(new HttpPut(getRequestUrl(url, sign, signKey)), datas);
  468. default:
  469. return sendHttpEntityEnclosingRequest(new HttpPost(getRequestUrl(url, sign, signKey)), datas);
  470. }
  471. }
  472. /**
  473. * 发起GET、DELETE请求
  474. *
  475. * @param request
  476. * @return
  477. * @throws Exception
  478. */
  479. private static Response sendHttpUriRequest(HttpRequestBase request) throws Exception {
  480. //采用绕过验证的方式处理https请求
  481. SSLContext sslcontext = createIgnoreVerifySSL();
  482. // 设置协议http和https对应的处理socket链接工厂的对象
  483. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  484. .register("http", PlainConnectionSocketFactory.INSTANCE)
  485. .register("https", new SSLConnectionSocketFactory(sslcontext))
  486. .build();
  487. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  488. HttpClients.custom().setConnectionManager(connManager);
  489. //创建自定义的httpclient对象
  490. CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
  491. //CloseableHttpClient httpClient = HttpClients.createDefault();
  492. CloseableHttpResponse response = null;
  493. try {
  494. response = httpClient.execute(request);
  495. return Response.getResponse(response);
  496. } finally {
  497. try {
  498. httpClient.close();
  499. } catch (IOException e) {
  500. }
  501. if (response != null) {
  502. try {
  503. response.close();
  504. } catch (IOException e) {
  505. }
  506. }
  507. }
  508. }
  509. /**
  510. * 发起POST、PUT请求
  511. *
  512. * @param request
  513. * @param params
  514. * @return
  515. * @throws Exception
  516. */
  517. private static Response sendHttpEntityEnclosingRequest(HttpEntityEnclosingRequestBase request, Map<String, String> params)
  518. throws Exception {
  519. //采用绕过验证的方式处理https请求
  520. SSLContext sslcontext = createIgnoreVerifySSL();
  521. // 设置协议http和https对应的处理socket链接工厂的对象
  522. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  523. .register("http", PlainConnectionSocketFactory.INSTANCE)
  524. .register("https", new SSLConnectionSocketFactory(sslcontext))
  525. .build();
  526. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  527. HttpClients.custom().setConnectionManager(connManager);
  528. //创建自定义的httpclient对象
  529. CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
  530. //CloseableHttpClient httpClient = HttpClients.createDefault();
  531. CloseableHttpResponse response = null;
  532. try {
  533. List<NameValuePair> nvps = new ArrayList<NameValuePair>();
  534. if (params != null && !params.isEmpty()) {
  535. Set<Entry<String, String>> entrys = params.entrySet();
  536. for (Map.Entry<String, String> entry : entrys) {
  537. nvps.add(new BasicNameValuePair(entry.getKey(), URLEncoder.encode(entry.getValue(), "UTF-8")));
  538. }
  539. }
  540. request.setEntity(new UrlEncodedFormEntity(nvps));
  541. response = httpClient.execute(request);
  542. return Response.getResponse(response);
  543. } finally {
  544. request.releaseConnection();
  545. try {
  546. httpClient.close();
  547. } catch (IOException e) {
  548. }
  549. if (response != null) {
  550. try {
  551. response.close();
  552. } catch (IOException e) {
  553. }
  554. }
  555. }
  556. }
  557. /**
  558. * 发起POST、PUT请求
  559. *
  560. * @param request
  561. * @param datas
  562. * @return
  563. * @throws Exception
  564. */
  565. private static Response sendHttpEntityEnclosingRequest(HttpEntityEnclosingRequestBase request, List<?> datas) throws Exception {
  566. //采用绕过验证的方式处理https请求
  567. SSLContext sslcontext = createIgnoreVerifySSL();
  568. // 设置协议http和https对应的处理socket链接工厂的对象
  569. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  570. .register("http", PlainConnectionSocketFactory.INSTANCE)
  571. .register("https", new SSLConnectionSocketFactory(sslcontext))
  572. .build();
  573. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  574. HttpClients.custom().setConnectionManager(connManager);
  575. //创建自定义的httpclient对象
  576. CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
  577. //CloseableHttpClient httpClient = HttpClients.createDefault();
  578. CloseableHttpResponse response = null;
  579. try {
  580. if (datas != null && !datas.isEmpty()) {
  581. request.setEntity(new StringEntity(FlexJsonUtil.toJsonArrayDeep(datas), ContentType.create("text/plain", Consts.UTF_8)));
  582. }
  583. response = httpClient.execute(request);
  584. return Response.getResponse(response);
  585. } finally {
  586. request.releaseConnection();
  587. try {
  588. httpClient.close();
  589. } catch (IOException e) {
  590. }
  591. if (response != null) {
  592. try {
  593. response.close();
  594. } catch (IOException e) {
  595. }
  596. }
  597. }
  598. }
  599. /**
  600. * 将请求参数添加到链接中
  601. *
  602. * @param url
  603. * @param params
  604. * @param sign
  605. * 是否签名
  606. * @return
  607. * @throws UnsupportedEncodingException
  608. */
  609. public static String getRequestUrl(String url, Map<String, String> params, boolean sign) throws UnsupportedEncodingException {
  610. StringBuilder buf = new StringBuilder(url);
  611. if (url.indexOf("?") == -1)
  612. buf.append("?");
  613. else if (!url.endsWith("&"))
  614. buf.append("&");
  615. // 如果是GET请求,则请求参数在URL中
  616. if (params != null && !params.isEmpty()) {
  617. Set<Entry<String, String>> entrys = params.entrySet();
  618. for (Map.Entry<String, String> entry : entrys) {
  619. buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&");
  620. }
  621. }
  622. if (sign) {
  623. // 加时间戳,保持相同请求每次签名均不一样
  624. buf.append("_timestamp=").append(System.currentTimeMillis());
  625. String message = buf.toString();
  626. // 对请求串进行签名
  627. buf.append("&_signature=").append(HmacUtils.encode(message));
  628. } else
  629. buf.deleteCharAt(buf.length() - 1);
  630. return buf.toString();
  631. }
  632. /**
  633. * 将请求参数添加到链接中
  634. *
  635. * @param url
  636. * @param params
  637. * @param sign
  638. * 是否签名
  639. * @param signKey
  640. * 签名密钥
  641. * @return
  642. * @throws UnsupportedEncodingException
  643. */
  644. public static String getRequestUrl(String url, Map<String, String> params, boolean sign, String signKey)
  645. throws UnsupportedEncodingException {
  646. if (sign && signKey == null)
  647. return getRequestUrl(url, params, sign);
  648. StringBuilder buf = new StringBuilder(url);
  649. if (url.indexOf("?") == -1)
  650. buf.append("?");
  651. else if (!url.endsWith("&"))
  652. buf.append("&");
  653. // 如果是GET请求,则请求参数在URL中
  654. if (params != null && !params.isEmpty()) {
  655. Set<Entry<String, String>> entrys = params.entrySet();
  656. for (Map.Entry<String, String> entry : entrys) {
  657. buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&");
  658. }
  659. }
  660. if (sign) {
  661. // 加时间戳,保持相同请求每次签名均不一样
  662. buf.append("_timestamp=").append(System.currentTimeMillis());
  663. String message = buf.toString();
  664. // 对请求串进行签名
  665. buf.append("&_signature=").append(HmacUtils.encode(message, signKey));
  666. } else
  667. buf.deleteCharAt(buf.length() - 1);
  668. return buf.toString();
  669. }
  670. /**
  671. * 将签名信息添加到链接中
  672. *
  673. * @param url
  674. * @param sign
  675. * 是否签名
  676. * @return
  677. * @throws UnsupportedEncodingException
  678. */
  679. private static String getRequestUrl(String url, boolean sign, String signKey) throws UnsupportedEncodingException {
  680. return getRequestUrl(url, null, sign, signKey);
  681. }
  682. /**
  683. * 将输入流转为字节数组
  684. *
  685. * @param inStream
  686. * @return
  687. * @throws Exception
  688. */
  689. public static byte[] read2Byte(InputStream inStream) throws Exception {
  690. ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
  691. byte[] buffer = new byte[1024];
  692. int len = 0;
  693. while ((len = inStream.read(buffer)) != -1) {
  694. outSteam.write(buffer, 0, len);
  695. }
  696. outSteam.close();
  697. inStream.close();
  698. return outSteam.toByteArray();
  699. }
  700. /**
  701. * 将输入流转为字符串
  702. *
  703. * @param inStream
  704. * @return
  705. * @throws Exception
  706. */
  707. public static String read2String(InputStream inStream) throws Exception {
  708. ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
  709. byte[] buffer = new byte[1024];
  710. int len = 0;
  711. while ((len = inStream.read(buffer)) != -1) {
  712. outSteam.write(buffer, 0, len);
  713. }
  714. try {
  715. outSteam.close();
  716. inStream.close();
  717. } catch (Exception e) {
  718. }
  719. return new String(outSteam.toByteArray(), "UTF-8");
  720. }
  721. /**
  722. * 发送xml数据
  723. *
  724. * @param path
  725. * 请求地址
  726. * @param xml
  727. * xml数据
  728. * @param encoding
  729. * 编码
  730. * @return
  731. * @throws Exception
  732. */
  733. public static byte[] postXml(String path, String xml, String encoding) throws Exception {
  734. byte[] data = xml.getBytes(encoding);
  735. URL url = new URL(path);
  736. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  737. conn.setRequestMethod("POST");
  738. conn.setDoOutput(true);
  739. conn.setRequestProperty("Content-Type", "text/xml; charset=" + encoding);
  740. conn.setRequestProperty("Content-Length", String.valueOf(data.length));
  741. conn.setConnectTimeout(5 * 1000);
  742. OutputStream outStream = conn.getOutputStream();
  743. outStream.write(data);
  744. outStream.flush();
  745. outStream.close();
  746. if (conn.getResponseCode() == HttpStatus.OK.value()) {
  747. return read2Byte(conn.getInputStream());
  748. }
  749. return null;
  750. }
  751. /**
  752. * http上传文件
  753. *
  754. * @param postUrl
  755. * 请求地址
  756. * @param filePath
  757. * 附件路径
  758. * @param params
  759. * 参数
  760. * @return
  761. * @throws Exception
  762. * @throws IOException
  763. * @throws IllegalStateException
  764. */
  765. public static Response upload(String postUrl, String filePath, Map<String, String> params, boolean sign, String signKey)
  766. throws IllegalStateException, IOException, Exception {
  767. CloseableHttpClient httpClient = null;
  768. CloseableHttpResponse response = null;
  769. try {
  770. httpClient = HttpClients.createDefault();
  771. HttpPost httpPost = new HttpPost(getRequestUrl(postUrl, sign, signKey));
  772. FileBody fileBody = new FileBody(new File(filePath));
  773. MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  774. builder.addPart("file", fileBody);
  775. if (params != null) {
  776. for (String paramKey : params.keySet()) {
  777. StringBody body = new StringBody(params.get(paramKey), ContentType.create("text/plain", Consts.UTF_8));
  778. builder.addPart(paramKey, body);
  779. }
  780. }
  781. HttpEntity reqEntity = builder.build();
  782. httpPost.setEntity(reqEntity);
  783. response = httpClient.execute(httpPost);
  784. } finally {
  785. try {
  786. if (response != null) {
  787. response.close();
  788. }
  789. } catch (IOException e) {
  790. e.printStackTrace();
  791. }
  792. try {
  793. if (httpClient != null) {
  794. httpClient.close();
  795. }
  796. } catch (IOException e) {
  797. e.printStackTrace();
  798. }
  799. }
  800. return Response.getResponse(response);
  801. }
  802. /**
  803. * http上传文件
  804. *
  805. * @param postUrl
  806. * 请求地址
  807. * @param file
  808. * 附件
  809. * @param params
  810. * 参数
  811. * @return
  812. * @throws Exception
  813. * @throws IOException
  814. * @throws IllegalStateException
  815. */
  816. public static Response upload(String postUrl, MultipartFile file, Map<String, String> params, boolean sign, String signKey)
  817. throws IllegalStateException, IOException, Exception {
  818. CloseableHttpClient httpClient = null;
  819. CloseableHttpResponse response = null;
  820. try {
  821. httpClient = HttpClients.createDefault();
  822. HttpPost httpPost = new HttpPost(getRequestUrl(postUrl, sign, signKey));
  823. InputStreamBody sbody = new InputStreamBody(file.getInputStream(), file.getOriginalFilename());
  824. MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  825. builder.addPart("file", sbody);
  826. if (params != null) {
  827. for (String paramKey : params.keySet()) {
  828. StringBody body = new StringBody(params.get(paramKey), ContentType.create("text/plain", Consts.UTF_8));
  829. builder.addPart(paramKey, body);
  830. }
  831. }
  832. HttpEntity reqEntity = builder.build();
  833. httpPost.setEntity(reqEntity);
  834. response = httpClient.execute(httpPost);
  835. } finally {
  836. try {
  837. if (response != null) {
  838. response.close();
  839. }
  840. } catch (IOException e) {
  841. e.printStackTrace();
  842. }
  843. try {
  844. if (httpClient != null) {
  845. httpClient.close();
  846. }
  847. } catch (IOException e) {
  848. e.printStackTrace();
  849. }
  850. }
  851. return Response.getResponse(response);
  852. }
  853. /**
  854. * 下载
  855. *
  856. * @param postUrl
  857. * @return
  858. * @throws ClientProtocolException
  859. * @throws IOException
  860. * @throws NoSuchAlgorithmException
  861. * @throws KeyManagementException
  862. */
  863. public static InputStream download(String postUrl) throws ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException {
  864. //采用绕过验证的方式处理https请求
  865. SSLContext sslcontext = createIgnoreVerifySSL();
  866. // 设置协议http和https对应的处理socket链接工厂的对象
  867. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  868. .register("http", PlainConnectionSocketFactory.INSTANCE)
  869. .register("https", new SSLConnectionSocketFactory(sslcontext))
  870. .build();
  871. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  872. HttpClients.custom().setConnectionManager(connManager);
  873. //创建自定义的httpclient对象
  874. CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
  875. //CloseableHttpClient httpClient = HttpClients.createDefault();
  876. HttpGet httpGet = new HttpGet(postUrl);
  877. CloseableHttpResponse response = httpClient.execute(httpGet);
  878. return response.getEntity().getContent();
  879. }
  880. public static class Response {
  881. private int statusCode;
  882. private String responseText;
  883. public int getStatusCode() {
  884. return statusCode;
  885. }
  886. public void setStatusCode(int statusCode) {
  887. this.statusCode = statusCode;
  888. }
  889. public String getResponseText() {
  890. return responseText;
  891. }
  892. public void setResponseText(String responseText) {
  893. this.responseText = responseText;
  894. }
  895. public Response() {
  896. }
  897. public Response(boolean success, String content) {
  898. super();
  899. this.statusCode = success ? 200 : 404;
  900. this.responseText = content;
  901. }
  902. public Response(HttpResponse response) throws IllegalStateException, IOException, Exception {
  903. this.statusCode = response.getStatusLine().getStatusCode();
  904. this.responseText = HttpUtil.read2String(response.getEntity().getContent());
  905. }
  906. public static Response getResponse(HttpResponse response) throws IllegalStateException, IOException, Exception {
  907. if (response != null)
  908. return new Response(response);
  909. return null;
  910. }
  911. }
  912. }