一、前言
在项目中,有时需要去调用其他服务的接口,那么我们可以通过httpClient来实现调用。
二、具体实现
1.首先定义一个httpClient的工具类
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class HttpClientUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
public static String doGet(String url, Map<String, String> param,Map<String, String> header) {
logger.info("doGetJson,param:{},header:{}",param,header);
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
//设置请求头
if (Objects.nonNull(header)) {
header.forEach((key, value) -> {
httpGet.addHeader(key, value);
});
}
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
logger.info("doGet error", e);
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url, Map<String, String> param, Map<String, String> hearder) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
//设置请求头
if (Objects.nonNull(hearder)) {
hearder.forEach((key, value) -> {
httpPost.addHeader(key, value);
});
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
logger.info("doPost error", e);
} finally {
try {
if (response != null) {
response.close();
}
httpClient.close();
} catch (IOException e) {
logger.info("doPost error", e);
}
}
return resultString;
}
public static String doPostJson(String url, String json,Map<String, String> hearder) throws Exception {
logger.info("doPostJson,json:{},header:{}",json,hearder);
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = null;
try {
// 对请求的配置,会覆盖全局配置
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接超时时间,单位毫秒,指完成三次tcp握手时间上限
.setConnectTimeout(60000)
// 读取超时,指从请求的网址获得响应数据的时间间隔
.setSocketTimeout(60000)
// 指从连接池里面获取响应数据的时间间隔
.setConnectionRequestTimeout(60000)
.build();
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);
//设置请求头
if (Objects.nonNull(hearder)) {
hearder.forEach((key, value) -> {
httpPost.addHeader(key, value);
});
}
//json
StringEntity entity = new StringEntity(json);
// 给Entity设置Content-Type
entity.setContentType(new BasicHeader("Content-Type", "application/json; charset=utf-8"));
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
logger.info("doPostJson error", e);
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
logger.info("doPostJson error", e);
}
}
return resultString;
}
}
2.接着我们可以通过这个工具类实现调用,定义一个服务类。
public class TestService{
public DataReturnModeTestlDto signApiConnect(AddParam param) {
//获取请求头
Map<String, String> header = param.getHeaders();
//获取请求体
Map<String, Object> body = param.getBody();
String url = param.getUrl();
Map<String, Object> requestParamMap = param.getRequestParam();
String requestMethod= param.getRequestMethod();
try {
//判断是get还是post请求
Map<String, Object> requstInfo = new HashMap<>();
dto.setRequstInfo(requstInfo);
requstInfo.put(HTTP_METH, requestMethod);
String responseBody = null;
if (BizConstants.HTTP_GET.equals(requestMethod)) {
//get请求
responseBody = HttpClientUtil.doGet(url, requstParam, header);
} else if (BizConstants.HTTP_POST.equals(requestMethod)) {
//post请求
responseBody = HttpClientUtil.doPostJson(url, JSON.toJSONString(body), header);
requstInfo.put(IP, url);
requstInfo.put(REQUEST_PARAM, body);
}
dto.setData(responseBody);
} catch (Exception exception) {
throw new BizException("请求失败");
}
return dto;
}
}
最后我们可以尝试调用下接口。