當前位置:
首頁 > 知識 > Http客戶端工具類

Http客戶端工具類

在平時工作中,我們經常會有請求介面的需求,抽時間總結了一下供大家參考。

依賴包:

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.5</version>
  5. </dependency>

工具類文件:

  1. package com.rz.util;
  2. import java.io.IOException;
  3. import java.io.UnsupportedEncodingException;
  4. import java.net.SocketTimeoutException;
  5. import java.net.URI;
  6. import java.net.URISyntaxException;
  7. import java.net.URL;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. import java.util.Map;
  11. import org.apache.commons.httpclient.HttpStatus;
  12. import org.apache.commons.lang3.StringUtils;
  13. import org.apache.http.HttpResponse;
  14. import org.apache.http.NameValuePair;
  15. import org.apache.http.ParseException;
  16. import org.apache.http.client.config.RequestConfig;
  17. import org.apache.http.client.entity.UrlEncodedFormEntity;
  18. import org.apache.http.client.methods.CloseableHttpResponse;
  19. import org.apache.http.client.methods.HttpDelete;
  20. import org.apache.http.client.methods.HttpGet;
  21. import org.apache.http.client.methods.HttpPost;
  22. import org.apache.http.client.methods.HttpPut;
  23. import org.apache.http.client.utils.URLEncodedUtils;
  24. import org.apache.http.entity.StringEntity;
  25. import org.apache.http.impl.client.CloseableHttpClient;
  26. import org.apache.http.impl.client.HttpClients;
  27. import org.apache.http.message.BasicNameValuePair;
  28. import org.apache.http.util.EntityUtils;
  29. import org.slf4j.Logger;
  30. import org.slf4j.LoggerFactory;
  31. import com.alibaba.fastjson.JSONObject;
  32. /**
  33. * HTTP客戶端幫助類
  34. */
  35. public class HttpClientUtil {
  36. private static final Logger LOG = LoggerFactory.getLogger(HttpClientUtil.class);
  37. public static final String CHAR_SET = "UTF-8";
  38. private static CloseableHttpClient httpClient;
  39. private static int socketTimeout = 30000;
  40. private static int connectTimeout = 30000;
  41. private static int connectionRequestTimeout = 30000;
  42. // 配置總體最大連接池(maxConnTotal)和單個路由連接最大數(maxConnPerRoute),默認是(20,2)
  43. private static int maxConnTotal = 200; // 最大不要超過1000
  44. private static int maxConnPerRoute = 100;// 實際的單個連接池大小,如tps定為50,那就配置50
  45. static {
  46. RequestConfig config = RequestConfig.custom()
  47. .setSocketTimeout(socketTimeout)
  48. .setConnectTimeout(connectTimeout)
  49. .setConnectionRequestTimeout(connectionRequestTimeout).build();
  50. httpClient = HttpClients.custom().setDefaultRequestConfig(config)
  51. .setMaxConnTotal(maxConnTotal)
  52. .setMaxConnPerRoute(maxConnPerRoute).build();
  53. }
  54. public static CloseableHttpClient getClient() {
  55. return httpClient;
  56. }
  57. public static String get(String url) {
  58. try {
  59. return get(url, null, null);
  60. } catch (IOException e) {
  61. LOG.error("HttpClientUtil.get()報錯:", e);
  62. }
  63. return null;
  64. }
  65. public static String get(String url, Map<String, String> map) {
  66. try {
  67. return get(url, map, null);
  68. } catch (IOException e) {
  69. LOG.error("HttpClientUtil.get()報錯:", e);
  70. }
  71. return null;
  72. }
  73. public static String get(String url, String charset) {
  74. try {
  75. return get(url, null, charset);
  76. } catch (IOException e) {
  77. LOG.error("HttpClientUtil.get()報錯:", e);
  78. }
  79. return null;
  80. }
  81. public static String get(String url, Map<String, String> paramsMap, String charset) throws IOException {
  82. if ( StringUtils.isBlank(url) ) {
  83. return null;
  84. }
  85. charset = (charset == null ? CHAR_SET : charset);
  86. if (null != paramsMap && !paramsMap.isEmpty()) {
  87. List<NameValuePair> params = new ArrayList<NameValuePair>();
  88. for (Map.Entry<String, String> map : paramsMap.entrySet()) {
  89. params.add(new BasicNameValuePair(map.getKey(), map.getValue()));
  90. }
  91. //GET方式URL參數編碼
  92. String querystring = URLEncodedUtils.format(params, charset);
  93. if(StringUtils.contains(url, "?")) {
  94. url += "&" + querystring;
  95. } else {
  96. url += "?" + querystring;
  97. }
  98. }
  99. HttpGet httpGet = new HttpGet(url);
  100. httpGet.addHeader("Accept-Encoding", "*");
  101. CloseableHttpResponse response = null;
  102. try {
  103. response = getClient().execute(httpGet);
  104. } catch (SocketTimeoutException e) {
  105. LOG.error("請求超時,1秒後將重試1次:"+ url, e);
  106. try {
  107. Thread.sleep(1000);
  108. } catch (InterruptedException e1) { }
  109. response = getClient().execute(httpGet);
  110. }
  111. // 狀態不為200的異常處理。
  112. return EntityUtils.toString(response.getEntity(), charset);
  113. }
  114. /**
  115. * 提供返回json結果的get請求(ESG專用)
  116. * @param url
  117. * @param charset
  118. * @return
  119. * @throws IOException */
  120. public static String getResponseJson(String url, Map<String, String> map) {
  121. try {
  122. return getResponseJson(url, map, null);
  123. } catch (IOException e) {
  124. LOG.error("HttpClientUtil.getResponseJson()報錯:", e);
  125. }
  126. return null;
  127. }
  128. public static String getResponseJson(String url, Map<String, String> paramsMap, String charset) throws IOException {
  129. if ( StringUtils.isBlank(url) ) {
  130. return null;
  131. }
  132. charset = (charset == null ? CHAR_SET : charset);
  133. if (null != paramsMap && !paramsMap.isEmpty()) {
  134. List<NameValuePair> params = new ArrayList<NameValuePair>();
  135. for (Map.Entry<String, String> map : paramsMap.entrySet()) {
  136. params.add(new BasicNameValuePair(map.getKey(), map.getValue()));
  137. }
  138. //GET方式URL參數編碼
  139. String querystring = URLEncodedUtils.format(params, charset);
  140. if(StringUtils.contains(url, "?")) {
  141. url += "&" + querystring;
  142. } else {
  143. url += "?" + querystring;
  144. }
  145. }
  146. HttpGet httpGet = new HttpGet(url);
  147. httpGet.addHeader("Accept-Encoding", "*");
  148. httpGet.addHeader("Accept", "application/json;charset=UTF-8");
  149. CloseableHttpResponse response = null;
  150. try {
  151. response = getClient().execute(httpGet);
  152. } catch (SocketTimeoutException e) {
  153. // LOG.error("請求超時,1秒後將重試1次:"+ url, e);
  154. LOG.error(e.getMessage()+ "請求超時,1秒後將重試1次:"+ url);
  155. try {
  156. Thread.sleep(1000);
  157. } catch (InterruptedException e1) { }
  158. response = getClient().execute(httpGet);
  159. }
  160. // 狀態不為200的異常處理。
  161. return EntityUtils.toString(response.getEntity(), charset);
  162. }
  163. public static String delete(String url, Map<String, String> paramsMap, String charset) throws IOException {
  164. if ( StringUtils.isBlank(url) ) {
  165. return null;
  166. }
  167. charset = (charset == null ? CHAR_SET : charset);
  168. if (null != paramsMap && !paramsMap.isEmpty()) {
  169. List<NameValuePair> params = new ArrayList<NameValuePair>();
  170. for (Map.Entry<String, String> map : paramsMap.entrySet()) {
  171. params.add(new BasicNameValuePair(map.getKey(), map.getValue()));
  172. }
  173. //GET方式URL參數編碼
  174. String querystring = URLEncodedUtils.format(params, charset);
  175. if(StringUtils.contains(url, "?")) {
  176. url += "&" + querystring;
  177. } else {
  178. url += "?" + querystring;
  179. }
  180. }
  181. HttpDelete httpDelete = new HttpDelete(url);
  182. httpDelete.addHeader("Accept-Encoding", "*");
  183. CloseableHttpResponse response = getClient().execute(httpDelete);
  184. // 狀態不為200的異常處理。
  185. return EntityUtils.toString(response.getEntity(), charset);
  186. }
  187. public static String post(String url, String request) {
  188. return post(url, request, null);
  189. }
  190. public static String post(String url, String request, String charset) {
  191. if ( StringUtils.isBlank(url) ) {
  192. return null;
  193. }
  194. String res = null;
  195. CloseableHttpResponse response = null;
  196. try {
  197. charset = (charset == null ? CHAR_SET : charset);
  198. StringEntity entity = new StringEntity(request, charset);
  199. HttpPost httpPost = new HttpPost(url);
  200. httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
  201. httpPost.addHeader("Accept-Encoding", "*");
  202. httpPost.setEntity(entity);
  203. try {
  204. response = getClient().execute(httpPost);
  205. } catch (SocketTimeoutException e) {
  206. LOG.error("請求超時,1秒後將重試1次:"+ url, e);
  207. try {
  208. Thread.sleep(1000);
  209. } catch (InterruptedException e1) { }
  210. response = getClient().execute(httpPost);
  211. }
  212. res = EntityUtils.toString(response.getEntity());
  213. // 狀態不為200的異常處理。
  214. } catch (ParseException e) {
  215. LOG.error("HTTP Post(), ParseException: ", e);
  216. } catch (IOException e) {
  217. LOG.error("HTTP Post(), IOException: ", e);
  218. } finally {
  219. if (response != null) {
  220. try {
  221. response.close();
  222. } catch (IOException e) {
  223. }
  224. }
  225. }
  226. return res;
  227. }
  228. public static String post(String url, Map<String, String> map) {
  229. return post(url, map, null);
  230. }
  231. public static String post(String url, Map<String, String> paramsMap, String charset) {
  232. if ( StringUtils.isBlank(url) ) {
  233. return null;
  234. }
  235. String res = null;
  236. CloseableHttpResponse response = null;
  237. try {
  238. charset = (charset == null ? CHAR_SET : charset);
  239. List<NameValuePair> params = new ArrayList<NameValuePair>();
  240. for (Map.Entry<String, String> map : paramsMap.entrySet()) {
  241. params.add(new BasicNameValuePair(map.getKey(), map.getValue()));
  242. }
  243. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, charset);
  244. HttpPost httpPost = new HttpPost(url);
  245. httpPost.addHeader("Accept-Encoding", "*");
  246. httpPost.setEntity(formEntity);
  247. try {
  248. response = getClient().execute(httpPost);
  249. } catch (SocketTimeoutException e) {
  250. LOG.error("請求超時,1秒後將重試1次:"+ url, e);
  251. try {
  252. Thread.sleep(1000);
  253. } catch (InterruptedException e1) { }
  254. response = getClient().execute(httpPost);
  255. }
  256. res = EntityUtils.toString(response.getEntity());
  257. // 狀態不為200的異常處理。
  258. if (response.getStatusLine().getStatusCode() != 200) {
  259. throw new IOException(res);
  260. }
  261. } catch (IOException e) {
  262. LOG.error("HTTP Post(), IOException: ", e);
  263. } finally {
  264. if (response != null) {
  265. try {
  266. response.close();
  267. } catch (IOException e) {
  268. }
  269. }
  270. }
  271. return res;
  272. }
  273. /**
  274. * 提供返回json結果的post請求
  275. * @param url
  276. * @param map
  277. * @param charset
  278. * @return json
  279. * @throws IOException */
  280. public static String postResponseJson(String url, Map<String, String> map) {
  281. return postResponseJson(url, map, null);
  282. }
  283. /**
  284. * Put方式提交
  285. * @param url
  286. * @param paramsMap
  287. * @param charset
  288. * @return response.getEntity() */
  289. public static String postResponseJson(String url, Map<String, String> paramsMap, String charset) {
  290. if ( StringUtils.isBlank(url) ) {
  291. return null;
  292. }
  293. String res = null;
  294. CloseableHttpResponse response = null;
  295. try {
  296. charset = (charset == null ? CHAR_SET : charset);
  297. List<NameValuePair> params = new ArrayList<NameValuePair>();
  298. for (Map.Entry<String, String> map : paramsMap.entrySet()) {
  299. params.add(new BasicNameValuePair(map.getKey(), map.getValue()));
  300. }
  301. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, charset);
  302. //解決url中的一些特殊字元
  303. URI uri = null;
  304. HttpPost httpPost = null;
  305. try {
  306. URL url2 = new URL(url);
  307. uri = new URI(url2.getProtocol(), url2.getUserInfo(), url2.getHost(), url2.getPort(), url2.getPath(), url2.getQuery(), null);
  308. } catch (URISyntaxException e) {
  309. LOG.error("URL中存在非法編碼:"+ url, e);
  310. uri = null;
  311. }
  312. if(uri != null) {
  313. httpPost = new HttpPost( uri );
  314. } else {
  315. httpPost = new HttpPost( url );
  316. }
  317. httpPost.addHeader("Accept-Encoding", "*");
  318. httpPost.addHeader("Accept", "application/json;charset=UTF-8");
  319. httpPost.setEntity(formEntity);
  320. try {
  321. response = getClient().execute(httpPost);
  322. } catch (SocketTimeoutException e) {
  323. // LOG.error("請求超時,1秒後將重試1次:"+ url, e);
  324. LOG.error(e.getMessage()+ "請求超時,1秒後將重試1次:"+ url);
  325. try {
  326. Thread.sleep(1000);
  327. } catch (InterruptedException e1) { }
  328. response = getClient().execute(httpPost);
  329. }
  330. res = EntityUtils.toString(response.getEntity());
  331. // 狀態不為200的異常處理。
  332. if (response.getStatusLine().getStatusCode() != 200) {
  333. throw new IOException(res);
  334. }
  335. } catch (IOException e) {
  336. LOG.error("postResponseJson方法報錯: ", e);
  337. } finally {
  338. if (response != null) {
  339. try {
  340. response.close();
  341. } catch (IOException e) {
  342. }
  343. }
  344. }
  345. return res;
  346. }
  347. /**
  348. * Put方式提交
  349. * @param url
  350. * @param paramsMap
  351. * @param charset
  352. * @return response.getEntity() */
  353. public static String put(String url, Map<String, String> paramsMap, String charset) {
  354. if ( StringUtils.isBlank(url) ) {
  355. return null;
  356. }
  357. String res = null;
  358. CloseableHttpResponse response = null;
  359. try {
  360. charset = (charset == null ? CHAR_SET : charset);
  361. List<NameValuePair> params = new ArrayList<NameValuePair>();
  362. for (Map.Entry<String, String> map : paramsMap.entrySet()) {
  363. params.add(new BasicNameValuePair(map.getKey(), map.getValue()));
  364. }
  365. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, charset);
  366. HttpPut httpPut = new HttpPut(url);
  367. httpPut.addHeader("Accept-Encoding", "*");
  368. httpPut.setEntity(formEntity);
  369. try {
  370. response = getClient().execute(httpPut);
  371. } catch (SocketTimeoutException e) {
  372. LOG.error("請求超時,1秒後將重試1次:"+ url, e);
  373. try {
  374. Thread.sleep(1000);
  375. } catch (InterruptedException e1) { }
  376. response = getClient().execute(httpPut);
  377. }
  378. res = EntityUtils.toString(response.getEntity());
  379. // 狀態不為200的異常處理。
  380. if (response.getStatusLine().getStatusCode() != 200) {
  381. throw new IOException(res);
  382. }
  383. } catch (IOException e) {
  384. LOG.error("HTTP put(), IOException: ", e);
  385. } finally {
  386. if (response != null) {
  387. try {
  388. response.close();
  389. } catch (IOException e) {
  390. }
  391. }
  392. }
  393. return res;
  394. }
  395. /**
  396. * Titel 提交HTTP請求,獲得響應(application/x-www-form-urlencoded) Description
  397. * 使用NameValuePair封裝參數,適用於下載文件。
  398. * @param serviceURI : 介面地址
  399. * @param timeOut : 超時時間
  400. * @param params : 請求參數
  401. * @param charset : 參數編碼
  402. * @return CloseableHttpResponse */
  403. public static CloseableHttpResponse submitPostHttpReq(final String serviceURI, final int timeOut,
  404. final Map<String, String> pmap, final String charset) {
  405. CloseableHttpResponse response = null;
  406. LOG.info("即將發起HTTP請求!serviceURI:" + serviceURI);
  407. // 遍歷封裝參數
  408. List<NameValuePair> formParams = new ArrayList<NameValuePair>();
  409. for (String key : pmap.keySet()) {
  410. NameValuePair pair = new BasicNameValuePair(key, pmap.get(key));
  411. formParams.add(pair);
  412. }
  413. // 轉換為from Entity
  414. UrlEncodedFormEntity fromEntity = null;
  415. try {
  416. fromEntity = new UrlEncodedFormEntity(formParams, CHAR_SET);
  417. } catch (UnsupportedEncodingException e) {
  418. LOG.error("創建UrlEncodedFormEntity異常,編碼問題: " + e.getMessage());
  419. return null;
  420. }
  421. // 創建http post請求
  422. HttpPost httpPost = new HttpPost(serviceURI);
  423. httpPost.setEntity(fromEntity);
  424. // 設置請求和傳輸超時時間
  425. RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();
  426. httpPost.setConfig(requestConfig);
  427. // 提交請求、獲取響應
  428. LOG.info("提交http請求!serviceURI:" + serviceURI);
  429. CloseableHttpClient httpclient = HttpClients.createDefault();
  430. try {
  431. response = httpclient.execute(httpPost);
  432. } catch (SocketTimeoutException e) {
  433. LOG.error("請求超時,1秒後將重試1次:"+ serviceURI, e);
  434. try {
  435. Thread.sleep(1000);
  436. response = httpclient.execute(httpPost);
  437. } catch (Exception e1) {
  438. LOG.error("超時後再次請求報錯:", e);
  439. response = null;
  440. }
  441. } catch (IOException e) {
  442. LOG.error("httpclient.execute異常!" + e.getMessage());
  443. response = null;
  444. }
  445. LOG.info("提交http請求!serviceURI:" + serviceURI);
  446. return response;
  447. }
  448. public static int getSocketTimeout() {
  449. return socketTimeout;
  450. }
  451. public static void setSocketTimeout(int socketTimeout) {
  452. HttpClientUtil.socketTimeout = socketTimeout;
  453. }
  454. public static int getConnectTimeout() {
  455. return connectTimeout;
  456. }
  457. public static void setConnectTimeout(int connectTimeout) {
  458. HttpClientUtil.connectTimeout = connectTimeout;
  459. }
  460. public static int getConnectionRequestTimeout() {
  461. return connectionRequestTimeout;
  462. }
  463. public static void setConnectionRequestTimeout(int connectionRequestTimeout) {
  464. HttpClientUtil.connectionRequestTimeout = connectionRequestTimeout;
  465. }
  466. /**
  467. * 請求josn串,返回josn對象
  468. * */
  469. public static JSONObject doPost(String url, String jsonStr) {
  470. HttpPost post = new HttpPost(url);
  471. JSONObject response = null;
  472. try {
  473. StringEntity s = new StringEntity(jsonStr,"UTF-8");
  474. s.setContentType("application/json");// 發送json數據需要設置contentType
  475. post.setEntity(s);
  476. HttpResponse res = getClient().execute(post);
  477. if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  478. String result = EntityUtils.toString(res.getEntity());// 返回json格式:
  479. response = JSONObject.parseObject(result);
  480. }
  481. } catch (Exception e) {
  482. throw new RuntimeException(e);
  483. }
  484. return response;
  485. }
  486. }

Http客戶端工具類

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

應用程序無法正常啟動0xc0150002解決方案
win7下tomcat8的配置

TAG:程序員小新人學習 |