百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

Http客户端工具类

toyiye 2024-06-21 12:09 10 浏览 0 评论

在平时工作中,我们经常会有请求接口的需求,抽时间总结了一下供大家参考。

依赖包:


  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. }

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码