经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
HttpClient详细使用示例代码
来源:jb51  时间:2022/7/20 13:09:16  对本文有异议

1、导入依赖

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.5.3</version>
  5. </dependency>
  6.  
  7. <dependency>
  8. <groupId>com.alibaba</groupId>
  9. <artifactId>fastjson</artifactId>
  10. <version>1.2.58</version>
  11. </dependency>
  12.  
  13. <dependency>
  14. <groupId>org.apache.httpcomponents</groupId>
  15. <artifactId>httpmime</artifactId>
  16. <version>4.5.3</version>
  17. </dependency>
  18.  
  19. <dependency>
  20. <groupId>org.apache.httpcomponents</groupId>
  21. <artifactId>httpcore</artifactId>
  22. <version>4.4.13</version>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.slf4j</groupId>
  26. <artifactId>slf4j-api</artifactId>
  27. <version>1.7.7</version>
  28. </dependency>

2、使用工具类

该工具类将get请求和post请求当中几种传参方式都写了,其中有get地址栏传参、get的params传参、post的params传参、post的json传参。

  1. import com.alibaba.fastjson.JSONObject;
  2. import org.apache.http.Consts;
  3. import org.apache.http.HttpEntity;
  4. import org.apache.http.HttpStatus;
  5. import org.apache.http.NameValuePair;
  6. import org.apache.http.client.ClientProtocolException;
  7. import org.apache.http.client.config.RequestConfig;
  8. import org.apache.http.client.entity.UrlEncodedFormEntity;
  9. import org.apache.http.client.methods.CloseableHttpResponse;
  10. import org.apache.http.client.methods.HttpGet;
  11. import org.apache.http.client.methods.HttpPost;
  12. import org.apache.http.client.utils.URIBuilder;
  13. import org.apache.http.entity.ContentType;
  14. import org.apache.http.entity.StringEntity;
  15. import org.apache.http.entity.mime.HttpMultipartMode;
  16. import org.apache.http.entity.mime.MultipartEntityBuilder;
  17. import org.apache.http.impl.client.CloseableHttpClient;
  18. import org.apache.http.impl.client.HttpClients;
  19. import org.apache.http.message.BasicNameValuePair;
  20. import org.apache.http.util.EntityUtils;
  21. import org.slf4j.Logger;
  22. import org.slf4j.LoggerFactory;
  23.  
  24. import java.io.*;
  25. import java.net.URI;
  26. import java.net.URISyntaxException;
  27. import java.nio.charset.Charset;
  28. import java.util.ArrayList;
  29. import java.util.List;
  30. import java.util.Map;
  31.  
  32. public class HttpClientUtil {
  33.  
  34. private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
  35.  
  36. private static final int DEFULT_TIMEOUT = 30 * 1000;//默认超时时间20秒
  37.  
  38. /**
  39. * 可以访问 http://localhost:9005/yzhwsj/addPersonal/1/2 这样的接口
  40. * @param url
  41. * @param headers
  42. * @param urlParam
  43. * @param timeout
  44. * @return
  45. */
  46. private static String doUrlGet(String url, Map<String, String> headers, List<String> urlParam, Integer timeout) {
  47. //创建httpClient对象
  48. CloseableHttpClient httpClient = HttpClients.createDefault();
  49. String resultString = null;
  50. CloseableHttpResponse response = null;
  51. try {
  52. //创建uri
  53. if (urlParam != null){
  54. for (String param : urlParam) {
  55. url = url + "/" + param;
  56. }
  57. }
  58. //创建hTTP get请求
  59. HttpGet httpGet = new HttpGet(url);
  60. //设置超时时间
  61. int timeoutTmp = DEFULT_TIMEOUT;
  62. if (timeout != null) {
  63. timeoutTmp = timeout;
  64. }
  65. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
  66. .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
  67. httpGet.setConfig(requestConfig);
  68. //设置头信息
  69. if (null != headers) {
  70. for (String key : headers.keySet()) {
  71. httpGet.setHeader(key, headers.get(key));
  72. }
  73. }
  74. //执行请求
  75. response = httpClient.execute(httpGet);
  76. if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
  77. resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
  78. }
  79. } catch (IOException e) {
  80. logger.error("http调用异常" + e.toString(), e);
  81. } finally {
  82. try {
  83. if (null != response) {
  84. response.close();
  85. }
  86. } catch (IOException e) {
  87. logger.error("response关闭异常" + e.toString(), e);
  88. }
  89. try {
  90. if (null != httpClient) {
  91. httpClient.close();
  92. }
  93. } catch (IOException e) {
  94. logger.error("httpClient关闭异常" + e.toString(), e);
  95. }
  96. }
  97. return resultString;
  98. }
  99.  
  100. /**
  101. * @param url
  102. * @param headers
  103. * @param params
  104. * @param timeout
  105. * @return
  106. */
  107. private static String doGet(String url, Map<String, String> headers, Map<String, Object> params, Integer timeout) {
  108. //创建httpClient对象
  109. CloseableHttpClient httpClient = HttpClients.createDefault();
  110. String resultString = null;
  111. CloseableHttpResponse response = null;
  112. try {
  113. // 1.创建uri
  114. URIBuilder builder = new URIBuilder(url);
  115. if (params != null) {
  116. //uri添加参数
  117. for (String key : params.keySet()) {
  118. builder.addParameter(key, String.valueOf(params.get(key)));
  119. }
  120. }
  121. URI uri = builder.build();
  122. // 2.创建hTTP get请求
  123. HttpGet httpGet = new HttpGet(uri);
  124. // 3.设置超时时间
  125. int timeoutTmp = DEFULT_TIMEOUT;
  126. if (timeout != null) {
  127. timeoutTmp = timeout;
  128. }
  129. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
  130. .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
  131. httpGet.setConfig(requestConfig);
  132. // 4.设置头信息
  133. if (null != headers) {
  134. for (String key : headers.keySet()) {
  135. httpGet.setHeader(key, headers.get(key));
  136. }
  137. }
  138. // 5.执行请求
  139. response = httpClient.execute(httpGet);
  140. if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
  141. resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
  142. }
  143. } catch (URISyntaxException e) {
  144. logger.error("http调用异常" + e.toString(), e);
  145. } catch (IOException e) {
  146. logger.error("http调用异常" + e.toString(), e);
  147.  
  148. } finally {
  149. try {
  150. if (null != response) {
  151. response.close();
  152. }
  153. } catch (IOException e) {
  154. logger.error("response关闭异常" + e.toString(), e);
  155. }
  156. try {
  157. if (null != httpClient) {
  158. httpClient.close();
  159. }
  160. } catch (IOException e) {
  161. logger.error("httpClient关闭异常" + e.toString(), e);
  162. }
  163. }
  164. return resultString;
  165. }
  166.  
  167. /**
  168. * 调用http post请求(json数据)
  169. *
  170. * @param url
  171. * @param headers
  172. * @param json
  173. * @return
  174. */
  175. public static String doJsonPost(String url, Map<String, String> headers, JSONObject json, Integer timeout) {
  176. CloseableHttpClient httpClient = HttpClients.createDefault();
  177. CloseableHttpResponse response = null;
  178. String resultString = "";
  179. try {
  180. // 1.创建http post请求
  181. HttpPost httpPost = new HttpPost(url);
  182. // 2.设置超时时间
  183. int timeoutTmp = DEFULT_TIMEOUT;
  184. if (timeout != null) {
  185. timeoutTmp = timeout;
  186. }
  187. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
  188. .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
  189. httpPost.setConfig(requestConfig);
  190. // 3.设置参数信息
  191. StringEntity s = new StringEntity(json.toString(), Consts.UTF_8);
  192. // 发送json数据需要设置的contentType
  193. s.setContentType("application/json");
  194. httpPost.setEntity(s);
  195. // 4.设置头信息
  196. if (headers != null) {
  197. for (String key : headers.keySet()) {
  198. httpPost.setHeader(key, headers.get(key));
  199. }
  200. }
  201. // 5.执行http请求
  202. response = httpClient.execute(httpPost);
  203. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  204. resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
  205. }
  206. } catch (UnsupportedEncodingException e) {
  207. logger.error("调用http异常" + e.toString(), e);
  208. } catch (ClientProtocolException e) {
  209. logger.error("调用http异常" + e.toString(), e);
  210. } catch (IOException e) {
  211. logger.error("调用http异常" + e.toString(), e);
  212. } finally {
  213. try {
  214. if (null != response) {
  215. response.close();
  216. }
  217. } catch (IOException e) {
  218. logger.error("关闭response异常" + e.toString(), e);
  219. }
  220. try {
  221. if (null != httpClient) {
  222. httpClient.close();
  223. }
  224. } catch (IOException e) {
  225. logger.error("关闭httpClient异常" + e.toString(), e);
  226. }
  227. }
  228. return resultString;
  229. }
  230.  
  231. /**
  232. * 调用http post请求 基础方法
  233. *
  234. * @param url 请求的url
  235. * @param headers 请求头
  236. * @param params 参数
  237. * @param timeout 超时时间
  238. * @return
  239. */
  240. public static String doPost(String url, Map<String, String> headers, Map<String, Object> params, Integer timeout) {
  241. CloseableHttpClient httpClient = HttpClients.createDefault();
  242. CloseableHttpResponse response = null;
  243. String resultString = "";
  244. try {
  245. // 1.创建http post请求
  246. HttpPost httpPost = new HttpPost(url);
  247. // 2.设置超时时间
  248. int timeoutTmp = DEFULT_TIMEOUT;
  249. if (timeout != null) {
  250. timeoutTmp = timeout;
  251. }
  252. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
  253. .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
  254. httpPost.setConfig(requestConfig);
  255. // 3.设置参数信息
  256. if (params != null) {
  257. List<NameValuePair> paramList = new ArrayList<>();
  258. for (String key : params.keySet()) {
  259. paramList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
  260. }
  261. // 模拟表单
  262. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, Consts.UTF_8);
  263. httpPost.setEntity(entity);
  264. }
  265. // 4.设置头信息
  266. if (headers != null) {
  267. for (String key : headers.keySet()) {
  268. httpPost.setHeader(key, headers.get(key));
  269. }
  270. }
  271. // 5.执行http请求
  272. response = httpClient.execute(httpPost);
  273. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  274. resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
  275. }
  276. } catch (UnsupportedEncodingException e) {
  277. logger.error("调用http异常" + e.toString(), e);
  278. } catch (ClientProtocolException e) {
  279. logger.error("调用http异常" + e.toString(), e);
  280. } catch (IOException e) {
  281. logger.error("调用http异常" + e.toString(), e);
  282. } finally {
  283. try {
  284. if (null != response) {
  285. response.close();
  286. }
  287. } catch (IOException e) {
  288. logger.error("关闭response异常" + e.toString(), e);
  289. }
  290. try {
  291. if (null != httpClient) {
  292. httpClient.close();
  293. }
  294. } catch (IOException e) {
  295. logger.error("关闭httpClient异常" + e.toString(), e);
  296. }
  297. }
  298. return resultString;
  299. }
  300. /**
  301. * 通过httpClient上传文件
  302. *
  303. * @param url 请求的URL
  304. * @param headers 请求头参数
  305. * @param path 文件路径
  306. * @param fileName 文件名称
  307. * @param timeout 超时时间
  308. * @return
  309. */
  310. public static String UploadFileByHttpClient(String url, Map<String, String> headers, String path, String fileName, Integer timeout) {
  311. String resultString = "";
  312. CloseableHttpClient httpClient = HttpClients.createDefault();
  313. CloseableHttpResponse response = null;
  314. InputStream content = null;
  315. BufferedReader in = null;
  316. try {
  317. // 1.创建http post请求
  318. HttpPost httpPost = new HttpPost(url);
  319.  
  320. // 2.设置超时时间
  321. int timeoutTmp = DEFULT_TIMEOUT;
  322. if (timeout != null) {
  323. timeoutTmp = timeout;
  324. }
  325. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
  326. .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
  327. httpPost.setConfig(requestConfig);
  328.  
  329. // 3.设置参数信息
  330. // HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
  331. MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
  332. // 上传文件的路径
  333. File file = new File(path + File.separator + fileName);
  334. builder.setCharset(Charset.forName("UTF-8"));
  335. builder.addBinaryBody("file", file, ContentType.MULTIPART_FORM_DATA, fileName);
  336. HttpEntity entity = builder.build();
  337. httpPost.setEntity(entity);
  338.  
  339. // 4.设置头信息
  340. if (headers != null) {
  341. for (String key : headers.keySet()) {
  342. httpPost.setHeader(key, headers.get(key));
  343. }
  344. }
  345.  
  346. // 5.执行http请求
  347. response = httpClient.execute(httpPost);
  348. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  349. resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
  350. }
  351. } catch (Exception e) {
  352. logger.error("上传文件失败:", e);
  353. } finally {
  354. try {
  355. if (null != httpClient) {
  356. httpClient.close();
  357. }
  358. } catch (IOException e) {
  359. logger.error("关闭httpClient异常" + e.toString(), e);
  360. }
  361. try {
  362. if (null != content) {
  363. content.close();
  364. }
  365. } catch (IOException e) {
  366. logger.error("关闭content异常" + e.toString(), e);
  367. }
  368. try {
  369. if (null != in) {
  370. in.close();
  371. }
  372. } catch (IOException e) {
  373. logger.error("关闭in异常" + e.toString(), e);
  374. }
  375. }
  376.  
  377. return resultString;
  378. }
  379. }
  380.  
  381. /**
  382. * 通过httpClient批量上传文件
  383. *
  384. * @param url 请求的URL
  385. * @param headers 请求头参数
  386. * @param params 参数
  387. * @param paths 文件路径(key文件名称,value路径)
  388. * @param timeout 超时时间
  389. * @return
  390. */
  391. public static String UploadFilesByHttpClient(String url, Map<String, String> headers, Map<String, String> params, Map<String, String> paths, Integer timeout) {
  392. String resultString = "";
  393. CloseableHttpClient httpClient = HttpClients.createDefault();
  394. CloseableHttpResponse response = null;
  395. InputStream content = null;
  396. BufferedReader in = null;
  397. try {
  398. // 1.创建http post请求
  399. HttpPost httpPost = new HttpPost(url);
  400.  
  401. // 2.设置超时时间
  402. int timeoutTmp = DEFULT_TIMEOUT;
  403. if (timeout != null) {
  404. timeoutTmp = timeout;
  405. }
  406. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
  407. .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
  408. httpPost.setConfig(requestConfig);
  409.  
  410. // 3.设置文件信息
  411. // HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
  412. MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
  413. builder.setCharset(Charset.forName("UTF-8"));
  414. // 上传文件的路径
  415. for (Map.Entry<String, String> m : paths.entrySet()) {
  416. File file = new File(m.getValue() + File.separator + m.getKey());
  417. builder.addBinaryBody("files", file, ContentType.MULTIPART_FORM_DATA, m.getKey());
  418. }
  419.  
  420. // 4.设置参数信息
  421. ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
  422. for (Map.Entry<String, String> param : params.entrySet()) {
  423. builder.addTextBody(param.getKey(), param.getValue(), contentType);
  424. }
  425. HttpEntity entity = builder.build();
  426. httpPost.setEntity(entity);
  427.  
  428. // 5.设置头信息
  429. if (headers != null) {
  430. for (String key : headers.keySet()) {
  431. httpPost.setHeader(key, headers.get(key));
  432. }
  433. }
  434.  
  435. // 6.执行http请求
  436. response = httpClient.execute(httpPost);
  437. if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  438. resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
  439. }
  440. } catch (Exception e) {
  441. logger.error("上传文件失败:", e);
  442. } finally {
  443. try {
  444. if (null != httpClient) {
  445. httpClient.close();
  446. }
  447. } catch (IOException e) {
  448. logger.error("关闭httpClient异常" + e.toString(), e);
  449. }
  450. try {
  451. if (null != content) {
  452. content.close();
  453. }
  454. } catch (IOException e) {
  455. logger.error("关闭content异常" + e.toString(), e);
  456. }
  457. try {
  458. if (null != in) {
  459. in.close();
  460. }
  461. } catch (IOException e) {
  462. logger.error("关闭in异常" + e.toString(), e);
  463. }
  464. }
  465.  
  466. return resultString;
  467. }

3、扩展

上面的工具类,方法都携带了token和超时时间,假如接口用不到可以做接口拓展。例如:

  1. /**
  2. * 调用http get请求
  3. *
  4. * @param url
  5. * @param params
  6. * @return
  7. */
  8. public static String doGet(String url, Map<String, Object> params) {
  9. return doGet(url, null, params, null);
  10. }

如果涉及到put请求和delete请求,跟上面都差不多,只不过创建请求的时候改为:

  1. HttpDelete httpDelete = new HttpDelete();
  2. HttpPut httpPut = new HttpPut();

到此这篇关于HttpClient详细使用示例的文章就介绍到这了,更多相关HttpClient使用内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号