1. pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>
<!--projectLombok Slf4j-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!--org.apache.httpcomponents/httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
2. src
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.List;
/**
* @author dzp
*/
@Slf4j
@Component
public class HttpUtil {
/**
* Http的get请求
*
* @param url url
* @param paramList get请求参数列表
* @param interfaceName 接口名称
* @return Http响应字符串
*/
public String doGet(String url, List<String> paramList, String interfaceName) {
// restful: ip:port/.../arg0/arg1/arg2...
if (!CollectionUtils.isEmpty(paramList)) {
StringBuilder sb = new StringBuilder(url);
paramList.forEach(e -> sb.append("/").append(e));
url = sb.toString();
}
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
try {
// 创建一个httpClient实例
httpClient = HttpClients.createDefault();
// 创建httpGet远程连接实例
HttpGet httpGet = new HttpGet(url);
// 配置请求参数实例
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接主机服务超时时间
.setConnectTimeout(1000 * 60 * 10)
// 设置连接请求超时时间
.setConnectionRequestTimeout(1000 * 60 * 10)
// 设置读取数据连接超时时间
.setSocketTimeout(1000 * 60 * 15)
.build();
// 为httpGet实例设置配置
httpGet.setConfig(requestConfig);
// httpClient对象执行get请求,并返回响应参数对象
long startTime = System.currentTimeMillis();
httpResponse = httpClient.execute(httpGet);
long endTime = System.currentTimeMillis();
// 从响应对象中获取响应内容
// 请求响应码
int resultCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity entity = httpResponse.getEntity();
// 通过EntityUtils中的toString方法将结果转换为字符串
String result = EntityUtils.toString(entity);
log.info("\n调用http的get请求, url: {}, 接口名称: {}, 响应参数: {}, 调用时长: {}",
url, interfaceName, result, (endTime - startTime) / 1000.0);
// 处理返回的数据
handleResponseData(startTime, endTime, resultCode, result);
return result;
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
// 关闭资源
closeResources(httpClient, httpResponse);
}
}
/**
* Http的post请求
*
* @param url url
* @param reqParamsJsonStr post请求参数的json字符串
* @param interfaceName 接口名称
* @return Http响应字符串
*/
public String doPost(String url, String reqParamsJsonStr, String interfaceName) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
try {
// 创建一个httpClient实例
httpClient = HttpClients.createDefault();
// 创建httpPost远程连接实例
HttpPost httpPost = new HttpPost(url);
// 配置请求参数实例
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接主机服务超时时间
.setConnectTimeout(1000 * 60 * 10)
// 设置连接请求超时时间
.setConnectionRequestTimeout(1000 * 60 * 10)
// 设置读取数据连接超时时间
.setSocketTimeout(1000 * 60 * 15)
.build();
// 为httpPost实例设置配置
httpPost.setConfig(requestConfig);
// 为httpPost设置封装好的请求参数
if (!StringUtils.isEmpty(reqParamsJsonStr)) {
StringEntity entityParam = new StringEntity(reqParamsJsonStr, "UTF-8");
entityParam.setContentEncoding("UTF-8");
entityParam.setContentType("application/json");
httpPost.setEntity(entityParam);
}
// httpClient对象执行post请求,并返回响应参数对象
long startTime = System.currentTimeMillis();
httpResponse = httpClient.execute(httpPost);
long endTime = System.currentTimeMillis();
// 从响应对象中获取响应内容
// 请求响应码
int resultCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity entity = httpResponse.getEntity();
// 通过EntityUtils中的toString方法将结果转换为字符串
String result = EntityUtils.toString(entity);
log.info("\n调用http的post请求, url: {}, 接口名称: {}, 请求参数:{}, 响应参数: {}, 调用时长: {}",
url, interfaceName, reqParamsJsonStr, result, (endTime - startTime) / 1000.0);
// 处理返回的数据
handleResponseData(startTime, endTime, resultCode, result);
return result;
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
// 关闭资源
closeResources(httpClient, httpResponse);
}
}
/**
* 处理http响应的数据
*
* @param startTime 时间戳
* @param endTime 时间戳
* @param resultCode http状态码
* @param result http响应结果
*/
private void handleResponseData(long startTime, long endTime, int resultCode, String result) {
if (resultCode != HttpStatus.SC_OK) {
log.info("Http请求失败! Http状态码为: {}", resultCode);
throw new IllegalStateException(String.format("Http请求失败! Http状态码为: %s", resultCode));
}
if (StringUtils.isEmpty(result)) {
log.info("Http状态码为: {}, 系统无信息返回, 请确认!", resultCode);
}
// 请求超时处理
if ((endTime - startTime) / 1000.0 >= 30.0) {
// TODO:请求超时处理
log.info("http请求超时");
}
}
/**
* 关闭资源
*
* @param httpClient CloseableHttpClient
* @param httpResponse CloseableHttpResponse
*/
private void closeResources(CloseableHttpClient httpClient, CloseableHttpResponse httpResponse) {
if (null != httpResponse) {
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}