本文介绍springboot中使用CloseableHttpClient类创建http连接
// 创建连接与设置连接参数 CloseableHttpClient httpClient = HttpClientBuilder.create().build();
直接上代码实现:
url为服务地址;map为请求参数;
后面有方法介绍
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
/**
* @Auther: zhouzihan
*/
@Component
@Slf4j
public class HttpComponentsClient {
static String resultData = null;
/**
* 调用服务端的POST请求
* 服务端入参注解: @RequestBody
*
* @param postUrl 设备服务请求地址
* @param map 设备对象参数<k,v>
* @throws Exception
*/
public static String doPost(String postUrl, Map<String, Object> map) throws Exception {
// 请求参数
String json = JSON.toJSONString(map);
// 创建连接与设置连接参数
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(postUrl);
StringEntity entity = new StringEntity(json);
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
// 发起请求与接收返回值
HttpResponse response = httpClient.execute(httpPost);
resultData = returnResult(response);
httpClient.close();
return resultData;
}
/**
* 调用服务端的GET请求
* 服务端入参注解: @RequestParam
*
* @param getUrl 设备服务请求地址
* @param map (支持单个、多个参数拼接)
* key:参数名称
* value:参数值
* @return resultData
* @throws Exception
*/
public static String doGetRequestParam(String getUrl, Map<String, Object> map) throws Exception {
String obj = questionMarksTheParticipation(map);
getUrl = getUrl + obj;
// 创建连接与设置连接参数
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(getUrl);
// 发起请求与接收返回值
HttpResponse response = httpClient.execute(httpGet);
resultData = returnResult(response);
httpClient.close();
return resultData;
}
/**
* 调用服务端的GET请求
* 服务端入参注解: @PathVariable
*/
public static String doGetPathVariable(String getUrl, Object val) throws Exception {
//入参有中文需要编码
getUrl = getUrl + val;
// 创建连接与设置连接参数
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(getUrl);
// 发起请求与接收返回值
HttpResponse response = httpClient.execute(httpGet);
resultData = returnResult(response);
httpClient.close();
return resultData;
}
/**
* 调用服务端的PUT请求
*
* @param map (支持单个、多个参数拼接)
* * key:参数名称
* * value:参数值
*/
public static String doPut(String getUrl, Map<String, Object> map) throws Exception {
//入参有中文需要编码
String obj = questionMarksTheParticipation(map);
getUrl = getUrl + obj;
// 创建连接与设置连接参数
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPut httpPut = new HttpPut(getUrl);
// 发起请求与接收返回值
HttpResponse response = httpClient.execute(httpPut);
resultData = returnResult(response);
httpClient.close();
return resultData;
}
/**
* 调用服务端的DELETE请求
*
* @param map (支持单个、多个参数拼接)
* * key:参数名称
* * value:参数值
*/
public static String doDelete(String getUrl, Map<String, Object> map) throws Exception {
//入参有中文需要编码
String obj = questionMarksTheParticipation(map);
getUrl = getUrl + obj;
// 创建连接与设置连接参数
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpDelete httpDelete = new HttpDelete(getUrl);
// 发起请求与接收返回值
HttpResponse response = httpClient.execute(httpDelete);
resultData = returnResult(response);
httpClient.close();
return resultData;
}
/**
* questionMarksTheParticipation():问号传参
*
* @param map key、value拼接 key或value存在空值跳过拼接
* 例:key=projectId
* value=1
* 参数拼接结果: ?projectId=1
* @return obj
*/
public static String questionMarksTheParticipation(Map<String, Object> map) throws UnsupportedEncodingException {
StringBuilder obj = new StringBuilder();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (null != entry.getKey() && null != entry.getValue()) {
if (!entry.getKey().isEmpty()) {
String s = entry.getKey() + "=" + URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8");
obj.append(s).append("&");
}
}
}
obj = new StringBuilder("?" + obj.substring(0, obj.length() - 1));
return obj.toString();
}
public static String returnResult(HttpResponse response) throws IOException {
if (response.getStatusLine().getStatusCode() != 200) {
log.error("调用服务端异常.");
}
HttpEntity res = response.getEntity();
String resultData = EntityUtils.toString(res);
log.info("从服务端返回结果: " + resultData);
return resultData;
}
}
注意:所有的方法传递参数的方式都是Map<String,Object>,这样做不需要关注外面对象的具体属性、参数属性个数。
直接把参数put到map中,在上面类中最后的两个方法questionMarksTheParticipation()和returnResult()已经将GET、PUT和DELETE请求参数做拼接处理,拼接到请求URL中了
/** * questionMarksTheParticipation():问号传参 * * @param map key、value拼接 key或value存在空值跳过拼接 * 例:key=projectId * value=1 * 参数拼接结果: ?projectId=1 * @return obj */ public static String questionMarksTheParticipation(Map<String, Object> map) throws UnsupportedEncodingException { StringBuilder obj = new StringBuilder(); for (Map.Entry<String, Object> entry : map.entrySet()) { if (null != entry.getKey() && null != entry.getValue()) { if (!entry.getKey().isEmpty()) { String s = entry.getKey() + "=" + URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"); obj.append(s).append("&"); } } } obj = new StringBuilder("?" + obj.substring(0, obj.length() - 1)); return obj.toString(); } public static String returnResult(HttpResponse response) throws IOException { if (response.getStatusLine().getStatusCode() != 200) { log.error("调用服务端异常."); } HttpEntity res = response.getEntity(); String resultData = EntityUtils.toString(res); log.info("从服务端返回结果: " + resultData); return resultData; }