Java HttpUtil 工具类 (使用 Apache HttpClient 包)
第一步 引入包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
第二步 创建基础工具类
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).
第三步 使用工具类
使用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);
使用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);
标签:Java,log,new,Apache,import,post,null,HttpUtil,response From: https://www.cnblogs.com/mlxs/p/16745361.html