HttpUtil.java 30 KB

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