HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性,它不仅使客户端发送Http请求变得容易,而且也方便开发人员测试接口(基于Http协议的),提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。
直接上代码
HttpConfig.java
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import java.util.concurrent.TimeUnit;
public class HttpConfig {
//首先实例化一个连接池管理器,设置最大连接数、并发连接数
private static final PoolingHttpClientConnectionManager manager;
//实例化连接
private static final CloseableHttpClient httpClient;
//实例化连接
private static final RequestConfig config = RequestConfig.custom()
.setConnectTimeout(5000)
.setConnectionRequestTimeout(6000)
.setSocketTimeout(60000)
.build();
static {
manager = new PoolingHttpClientConnectionManager();
//最大连接数
manager.setMaxTotal(128);
//并发数
manager.setDefaultMaxPerRoute(16);
// 检查间隔为5秒
manager.setValidateAfterInactivity(5000);
// 关闭空闲连接的时间为60S
manager.closeIdleConnections(60, TimeUnit.SECONDS);
httpClient = HttpClients.custom()
// 设置连接池
.setConnectionManager(manager)
// 设置超时时间
.setDefaultRequestConfig(config)
// 关闭自动重试
.disableAutomaticRetries()
.build();
}
/**
* 注入连接池,用于获取PoolingHttpClientConnectionManager
*
* @return PoolingHttpClientConnectionManager
*/
public static PoolingHttpClientConnectionManager manager() {
return manager;
}
/**
* 注入连接池,用于获取httpClient
*
* @return CloseableHttpClient
*/
public static CloseableHttpClient client() {
return httpClient;
}
/**
* 使用builder构建一个RequestConfig对象
*
* @return CloseableHttpClient
*/
public static RequestConfig config() {
return config;
}
}
HttpUtil.java
import cn.hutool.core.map.MapUtil;
import com.ruoyi.framework.config.HttpConfig;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@SuppressWarnings("all")
public class HttpUtil {
private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
/**
* 不带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
*
* @param url
*/
public static String doGet(String url) {
log.info("httpGet_url==>{}", url);
// 声明 http get 请求
HttpGet httpGet = new HttpGet(url);
// 装载配置信息
httpGet.setConfig(HttpConfig.config());
// 发起请求
try {
CloseableHttpResponse response = HttpConfig.client().execute(httpGet);
// 判断状态码是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 返回响应体的内容
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
log.info("httpGet_result==>{}", result);
return result;
}
} catch (Exception e) {
log.error("httpGet_error==>", e);
return null;
}
return null;
}
/**
* 带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
*
* @param url
*/
public static String doGet(String url, Map<String, Object> map) {
URIBuilder uriBuilder = null;
try {
uriBuilder = new URIBuilder(url);
if (map != null) {
// 遍历map,拼接请求参数
for (Map.Entry<String, Object> entry : map.entrySet()) {
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}
return doGet(uriBuilder.build().toString());
} catch (Exception e) {
return null;
}
}
/**
* 不带参数post请求
*
* @param url
* @return string json串
* @throws Exception
*/
public static String doPost(String url) {
return doPost(url, MapUtil.empty(), null);
}
public static String doPost(String url, Map<String, Object> map) {
return doPost(url, map, null);
}
/**
* 带map参数的post请求
*
* @param url
* @param map
* @return string json串
* @throws Exception
*/
public static String doPost(String url, Map<String, Object> map, Map<String, String> headers) {
log.info("httpPost_url==>{},params==>{}", url, map);
// 声明httpPost请求
HttpPost httpPost = new HttpPost(url);
// 加入配置信息
httpPost.setConfig(HttpConfig.config());
try {
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
// 判断map是否为空,不为空则进行遍历,封装from表单对象
if (map != null && !map.isEmpty()) {
List<NameValuePair> list = new ArrayList<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
// 构造from表单对象
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
// 把表单放到post里
httpPost.setEntity(urlEncodedFormEntity);
}
// 发起请求
try (CloseableHttpResponse response = HttpConfig.client().execute(httpPost)) {
if (response.getStatusLine().getStatusCode() == 200) {
// 返回响应体的内容
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
log.info("httpPost_result==>{}", result);
return result;
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
return null;
}
/**
* 带json参数的post请求,用的最多,因为map可以转为json
*
* @param url 请求地址host+path
* @param json json字符串
* @return string json串
*/
public static String doPost(String url, String json) {
return doPost(url, json, null);
}
/**
* 带json参数的post请求,用的最多,因为map可以转为json
*
* @param url 请求地址host+path
* @param json json字符串
* @return string json串
*/
public static String doPost(String url, String json, Map<String, String> headers) {
log.info("httpPost_url==>{},json==>{}", url, json);
//设置请求路径,请求格式,配置信息
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
httpPost.setConfig(HttpConfig.config());
// 发起请求
try {
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
//格式化请求数据并设值
StringEntity se = new StringEntity(json, "UTF-8");
se.setContentType("text/json");
httpPost.setEntity(se);
CloseableHttpResponse response = HttpConfig.client().execute(httpPost);
// 判断状态码是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 返回响应体的内容
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
log.info("httpPost_result==>{}", result);
return result;
}
} catch (Exception e) {
log.error("httpPost_error==>", e);
return null;
}
return null;
}
}