Http请求连接池工具类
程序员文章站
2022-06-01 13:52:11
...
springboot封装httpClient配置
该代码是在原博文基础之上修改了部分代码,使之易用,简化开发:原博文地址:springboot封装httpClient配置
使用场景:参数为body,并需要设置Header头部信息
1、添加pom内容
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
</dependency>
2、配置properties文件
application.properties
#http配置服务
#最大连接数
http.maxTotal = 100
#并发数
http.defaultMaxPerRoute = 20
#创建连接的最长时间
http.connectTimeout=1000
#从连接池中获取到连接的最长时间
http.connectionRequestTimeout=500
#数据传输的最长时间
http.socketTimeout=10000
#提交请求前测试连接是否可用
http.staleConnectionCheckEnabled=true
3、建立Client实体类
@Configuration
public class HttpClient {
@Value("${http.maxTotal}")
private Integer maxTotal;
@Value("${http.defaultMaxPerRoute}")
private Integer defaultMaxPerRoute;
@Value("${http.connectTimeout}")
private Integer connectTimeout;
@Value("${http.connectionRequestTimeout}")
private Integer connectionRequestTimeout;
@Value("${http.socketTimeout}")
private Integer socketTimeout;
@Value("${http.staleConnectionCheckEnabled}")
private boolean staleConnectionCheckEnabled;
/**
* 首先实例化一个连接池管理器,设置最大连接数、并发连接数
* @return
*/
@Bean(name = "httpClientConnectionManager")
public PoolingHttpClientConnectionManager getHttpClientConnectionManager(){
PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager();
//最大连接数
httpClientConnectionManager.setMaxTotal(maxTotal);
//并发数
httpClientConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
return httpClientConnectionManager;
}
/**
* 实例化连接池,设置连接池管理器。
* 这里需要以参数形式注入上面实例化的连接池管理器
* @param httpClientConnectionManager
* @return
*/
@Bean(name = "httpClientBuilder")
public HttpClientBuilder getHttpClientBuilder(@Qualifier("httpClientConnectionManager")PoolingHttpClientConnectionManager httpClientConnectionManager){
//HttpClientBuilder中的构造方法被protected修饰,所以这里不能直接使用new来实例化一个HttpClientBuilder,可以使用HttpClientBuilder提供的静态方法create()来获取HttpClientBuilder对象
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setConnectionManager(httpClientConnectionManager);
return httpClientBuilder;
}
/**
* 注入连接池,用于获取httpClient
* @param httpClientBuilder
* @return
*/
@Bean
public CloseableHttpClient getCloseableHttpClient(@Qualifier("httpClientBuilder") HttpClientBuilder httpClientBuilder){
return httpClientBuilder.build();
}
/**
* Builder是RequestConfig的一个内部类
* 通过RequestConfig的custom方法来获取到一个Builder对象
* 设置builder的连接信息
* 这里还可以设置proxy,cookieSpec等属性。有需要的话可以在此设置
* @return
*/
@Bean(name = "builder")
public RequestConfig.Builder getBuilder(){
RequestConfig.Builder builder = RequestConfig.custom();
return builder.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectionRequestTimeout)
.setSocketTimeout(socketTimeout)
.setStaleConnectionCheckEnabled(staleConnectionCheckEnabled);
}
/**
* 使用builder构建一个RequestConfig对象
* @param builder
* @return
*/
@Bean
public RequestConfig getRequestConfig(@Qualifier("builder") RequestConfig.Builder builder){
return builder.build();
}
}
4.
@Component
public class IdleConnectionEvictor extends Thread {
@Autowired
private HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionEvictor() {
super();
super.start();
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// 关闭失效的连接
connMgr.closeExpiredConnections();
}
}
} catch (InterruptedException ex) {
// 结束
}
}
//关闭清理无效连接的线程
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
5.设置返回信息格式
public class HttpResult {
// 响应码
private Integer code;
// 响应体
private String body;
public HttpResult() {
super();
}
public HttpResult(Integer code, String body) {
super();
this.code = code;
this.body = body;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
6.开始实现方法
import com.alibaba.fastjson.JSONObject;
import com.fsk.mallServiceTrade.utils.SignUtil;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @description: Http请求带有连接池的工具类
* @author: Cc
* @data: 2020/6/10 14:14
*/
@Component
public class HttpAPIService {
@Autowired
private CloseableHttpClient httpClient;
@Autowired
private RequestConfig config;
/**
* @description: 不带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
* @param url
* @return: java.lang.String
* @author: cc
* @date: 2020/6/10 15:23
**/
public String doGet(String url) throws Exception {
// 声明 http get 请求
HttpGet httpGet = new HttpGet(url);
// 装载配置信息
httpGet.setConfig(config);
// 发起请求
CloseableHttpResponse response = this.httpClient.execute(httpGet);
// 判断状态码是否为200
if (response.getStatusLine().getStatusCode() == 200) {
// 返回响应体的内容
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
return null;
}
/**
* @description: 带参数的get请求,如果状态码为200,则返回body,如果不为200,则返回null
* @param url
* @param map
* @return: java.lang.String
* @author: cc
* @date: 2020/6/10 15:22
**/
public String doGet(String url, Map<String, Object> map) throws Exception {
URIBuilder uriBuilder = new URIBuilder(url);
if (map != null) {
// 遍历map,拼接请求参数
for (Map.Entry<String, Object> entry : map.entrySet()) {
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
}
}
// 调用不带参数的get请求
return this.doGet(uriBuilder.build().toString());
}
/**
* @description: 带参数的post请求
* @param url
* @param map
* @return: com.alibaba.fastjson.JSONObject
* @author: cc
* @date: 2020/6/10 15:22
**/
public JSONObject doPost(String url, Map<String, Object> map) throws Exception {
// 声明httpPost请求
HttpPost httpPost = new HttpPost(url);
// 加入配置信息
httpPost.setConfig(config);
//添加请求头信息
Map<String, String> header = SignUtil.getHeader();
//设置Header
for (Map.Entry<String, String> cmap :header.entrySet()){
httpPost.addHeader(cmap.getKey(),cmap.getValue());
}
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
// 判断map是否为空,不为空则进行遍历,封装from表单对象
if (map != null) {
/* 如果是url后面追加参数,采用这种格式
List<NameValuePair> list = new ArrayList<NameValuePair>();
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");*/
//body里添加参数,使用这种方式
JSONObject jsonObject = new JSONObject(map);
// 把表单放到post里
httpPost.setEntity(new StringEntity(jsonObject.toJSONString()));
}
// 发起请求
CloseableHttpResponse response = this.httpClient.execute(httpPost);
HttpResult httpResult = new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity(), "UTF-8"));
String body = httpResult.getBody();
return JSONObject.parseObject(body);
}
/**
* @description: 不带参数post请求
* @param url
* @return: com.alibaba.fastjson.JSONObject
* @author: cc
* @date: 2020/6/10 15:22
**/
public JSONObject doPost(String url) throws Exception {
return this.doPost(url, null);
}
}
7.测试
import com.alibaba.fastjson.JSONObject;
import com.fsk.mallServiceTrade.utils.http.HttpAPIService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MallServiceTradeServiceApplicationTests {
@Autowired
private HttpAPIService httpAPIService;
@Test
public void contextLoads() throws Exception {
Map cMap = new HashMap<>();
cMap.put("ottCode","0033d8e5e36745d38c7e0e73fcb4883c");
JSONObject jsonObject = httpAPIService.doPost("https://www.ruibxx.com/chroDisea_test/api/authc/ottAuthor", cMap);
System.out.println(jsonObject);
}
}
8.返回信息
{“code”:1,“data”:{“phone”:“138xxxxx”,“avatar”:“https://www.baidu.com”,“userId”:“0033d8e5e36745d38c7e0e73fcb4883c”,“coin”:0},“message”:“操作成功”}
上一篇: 数据结构——链式栈模板类实现
下一篇: swing做的程序启动界面