HttpUtil.java 29 KB

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