Java HttpUtil 工具类 (使用 Apache HttpClient 包)

1|0Java HttpUtil 工具类 (使用 Apache HttpClient 包)

1|1第一步 引入包

 

<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency>

 

1|2第二步 创建基础工具类

 

package io.supers.common.utils; import cn.hutool.core.map.MapUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.Map; /** * @author guoc * @date 2022年08月16日 16:19 */ @Slf4j public class HttpUtil { public static JSONObject get(final String url, final Map<String, Object> params) { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; StringBuilder urlBuilder = new StringBuilder(url); urlBuilder.append("?"); if (MapUtil.isNotEmpty(params)) { for (Map.Entry<String, Object> p : params.entrySet()) { urlBuilder.append(p.getKey()).append("=").append(p.getValue()).append("&"); } } try { HttpGet httpGet = new HttpGet(); httpGet.setURI(new URI(urlBuilder.substring(0, urlBuilder.length() - 1))); log.info("\nGET 地址为:" + httpGet.getURI().toString()); response = httpClient.execute(httpGet); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); log.debug("\nGET 响应状态为:" + response.getStatusLine()); if (responseEntity != null) { String entityStr = EntityUtils.toString(responseEntity); log.debug("\nGET 响应内容: " + entityStr); log.debug("\nGET 响应内容长度为:" + responseEntity.getContentLength()); return JSON.parseObject(entityStr); } } catch (Exception e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } public static JSONObject post(HttpPost httpPost) { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; try { log.info("\nPOST 地址为: " + httpPost.getURI().toString()); log.info("\nPOST 请求头为: " + Arrays.toString(httpPost.getAllHeaders())); log.info("\nPOST 内容为: " + httpPost.getEntity()); // 由客户端执行(发送)Post请求 response = httpClient.execute(httpPost); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); log.debug("\nPOST 响应状态为:" + response.getStatusLine()); if (responseEntity != null) { String entityStr = EntityUtils.toString(responseEntity); log.debug("\nPOST 响应内容: " + entityStr); log.debug("\nPOST 响应内容长度为:" + responseEntity.getContentLength()); return JSON.parseObject(entityStr); } } catch (IOException e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } }

 

基础工具类用到了 hutool包, alibaba 的 fastjson 包,以及lombok 包, 引用为

 

<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.4.M1</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </dependency>

 

基础工具类 提供了两个方法 get(url,params) 和 post(httpPost).

1|3第三步 使用工具类

1|0使用Get请求

例如, 需要请求地址 http://aaa.com/a/b?c=d&e=f ,代码示例为

 

String url = "http://aaa.com/a/b"; Map<String, Object> params = MapUtil.newHashMap(); params.put("c", "d"); params.put("e", "f"); JSONObject jsonObject = get(url, params); System.out.println(jsonObject);

 

1|0使用Post请求

例如,需要请求地址 https://bbb.com/c/d?e=f , 并且需要传入UTF-8编码JSON格式的requestbody( {"g":"h","i":"j"} ),代码示例为

 

HttpPost post = new HttpPost(); // 注意这里的地址 跟 get请求不同 需要把参数直接拼接起来 (一般post请求不带地址栏参数,但此工具方法也需要支持传地址栏参数) post.setURI(URI.create("https://bbb.com/c/d?e=f")); // 为确保接收端能接收到正确编码的 requestBody 尽量加上header 设置 post.setHeader(new BasicHeader("Content-Type", "application/json;charset=UTF-8")); // 设置 StringEntity 时, 也需要设置编码, 此处的编码设置***非常重要*** post.setEntity(new StringEntity("{\"g\":\"h\",\"i\":\"j\"}", StandardCharsets.UTF_8)); JSONObject jsonObject = post(post); System.out.println(jsonObject);

 

若是接收端接收的不是JSON格式的数据, 而是表单格式的 requestBody, 则代码需要改为

 

HttpPost post = new HttpPost(); // 注意这里的地址 跟 get请求不同 需要把参数直接拼接起来 (一般post请求不带地址栏参数,但此工具方法也需要支持传地址栏参数) post.setURI(URI.create("https://bbb.com/c/d?e=f")); post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded")); List<NameValuePair> pairs = CollUtil.newArrayList(); pairs.add(new BasicNameValuePair("g", "h")); pairs.add(new BasicNameValuePair("i", "j")); post.setEntity(new UrlEncodedFormEntity(pairs, StandardCharsets.UTF_8)); JSONObject jsonObject = post(post); System.out.println(jsonObject);

 

 


__EOF__

本文作者MLXS
本文链接https://www.cnblogs.com/mlxs/p/16745361.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   莫傷曉  阅读(1845)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示