公司最近引入了反欺诈应用,通过aop的形式引入的,其中一个环节要调用第三方的接口,然后我直接写了,老大看到调用接口的逻辑,都是一样的,所以就叫我写个工具类,用于调用第三方的接口。
首先要引入相关的apache的Htttpclient的jar,因为公司使用springcloud,所以就用到了打印日志的logback。具体代码和使用案列如下,具体解释在代码注释中。
HttpClientUtils:
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Map;
public class HttpClientUtils {
//logback用于打印日志
private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
/**
* 获取httpclient
* CloseableHttpClient 是 Httpclient接口的一个实现类,
* 是可以关闭的http客户端
* @param maxTotal
* @param defaltMaxPerRoute
* @param connectTimeout
* @param socketTimeout
* @param connectionReuestTimeout
* @return
*/
public static CloseableHttpClient getHttpClient(int maxTotal, int defaltMaxPerRoute, int connectTimeout
, int socketTimeout, int connectionReuestTimeout){
//HttpClient池连接管理
PoolingHttpClientConnectionManager phccm = new PoolingHttpClientConnectionManager();
phccm.setMaxTotal(maxTotal);//设置HttpClient池的最大连接数
phccm.setDefaultMaxPerRoute(defaltMaxPerRoute);//设置默认的每个路由最大的连接数
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)//设置建立连接超时的时间 单位是ms
.setSocketTimeout(socketTimeout)//设置等待数据的超时时间
.setConnectionRequestTimeout(connectionReuestTimeout)
.build();//设置从连接池种拿连接的超时时间
//获取httpclent
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(phccm)
.setDefaultRequestConfig(requestConfig).build();
return httpClient;
}
/**
* 发送post请求
* @param httpClient
* @param url
* @param params 可以传object类型的参数
* @param charSet java nio中的charset
* @return
*/
public static CloseableHttpResponse sendPost(HttpClient httpClient, String url, Map<String, Object> params, Charset charSet){
CloseableHttpResponse response = null;
HttpPost httpPost = new HttpPost(url);
if(params != null && !params.isEmpty()){
StringEntity stringEntity = new StringEntity(JSON.toJSONString(params),charSet);
httpPost.setEntity(stringEntity);
httpPost.setHeader("Connection", "Close");//header由服务端自动关闭.防止服务端出现大量Close_Wait
}
try{
//注意这里给外面提供response结果,不能在这里关闭,不然调用改方法的
//地方会出现socket已经关闭的异常。
response = (CloseableHttpResponse)httpClient.execute(httpPost);
}catch (Exception e){
//logback用于打印日志,如果没有可以用log4j或者就直接打印System.out.println("xxx")
logger.error("sendPost error, for details: ",e);
}
return response;
}
/**
* 发送get请求
* @param httpClient
* @param url
* @param params
* @param charSet
* @return
*/
public static CloseableHttpResponse sendGet(HttpClient httpClient, String url, Map<String, String> params, Charset charSet){
CloseableHttpResponse response = null;
HttpGet httpGet = new HttpGet(url);
URIBuilder uriBuilder = new URIBuilder(httpGet.getURI());
try{
if(params != null && !params.isEmpty()){
Iterator it = params.entrySet().iterator();
while (it.hasNext()){
Map.Entry<String,String> entry = (Map.Entry<String, String>) it.next();
//get请求的参数是键值对形式的
uriBuilder.addParameter(entry.getKey(),entry.getValue());
}
URI uri = uriBuilder.build();
httpGet.setURI(uri);
}
response = (CloseableHttpResponse)httpClient.execute(httpGet);
}catch (Exception e){
logger.error("sendGet error, for details: ",e);
}
return response;
}
}
测试用例:
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
public class Test {
private static Logger logger = LoggerFactory.getLogger(Test.class);
public static final void main(String[] args){
HttpClient httpClient = HttpClientUtils.getHttpClient(10,2,1000,1000,1000);
CloseableHttpResponse response = null;
try{
response = HttpClientUtils.sendGet(httpClient,"https://mp.csdn.net/postedit/79397017",null, StandardCharsets.UTF_8);
if(response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
System.out.print(EntityUtils.toString(response.getEntity()));
}
}catch (Exception e){
logger.error("get https://mp.csdn.net/postedit/79397017 error, for details: ",e);
}finally {
if(response != null){
try {
//CloseableHttpResponse可以关闭,如果是Response接口则没有提供关闭的方法
//如果你创建的Httpclient是可以关闭的CloseableHttpClient,那么可以通过将
//reponse强转成CloseableHttpResponse进行关闭,如果不是那么会出现强转异常
response.close();
}catch (Exception e){
logger.error("response close error, for details: ",e);
}
}
}
}
}
这里我没有传参数,直接调用的一个get请求,如果传参数的话,Get请求:
Map<String,String> paramsMap = new HashMap<>();
paramsMap.put("xxx","xxxx");
即可。
Post请求:
Map<String,Object> paramsMap = new HashMap<>();
paramsMap.put("xxx", object);
这个object可以是个字符串也可以是个对象。我这里传参数的时候本来是用到 BasicNameValuePair,
但是这个要求是个string的键值对,而刚好我又需要传object对像,无法满足我的使用,所以就使用了StringEntity的方式。
CloseableHttpResponse这个响应要进行关闭,防止资源泄露。