在日常的开发中,去请求别的三方接口,现在有了一个很便捷的工具类:HttpComponents中的
1. 添加依赖包
HttpClient类属于org.apache.httpcomponents包中
<!-- httpclient 网络请求-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
2. 简单使用
1). 以json格式参数发送post请求
/**
* 发送json格式的post请求
* @param url 请求地址,如:https://www.baidu.com/insterface
* @param headerMap 请求头,以map型式拼装
* @param jsonObject fastjson中的JSONObject对象
* @return String json字符串,自行转换
*/
public static String sendJsonPost(String url, Map<String, String> headerMap, JSONObject jsonObject) {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost对象
HttpPost post = new HttpPost(url);
// 拼装Header
if (headerMap != null) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
post.setHeader(entry.getKey(), entry.getValue());
}
}
// 创建接收响应对象
CloseableHttpResponse response = null;
// 进行请求
try {
// 设置参数
StringEntity s = new StringEntity(jsonObject.toString());
s.setContentType("application/json");
s.setContentEncoding("UTF-8");
post.setEntity(s);
// 发送请求,获取响应
response = httpClient.execute(post);
System.out.println(response);
// 解析响应数据
if(response != null) {
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, "UTF-8");
}
// 捕获异常
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
// 先关闭httpClient
httpClient.close();
// 再关闭response
if(response != null) response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
2). 以userId=333&name=777的字符串参数发送post请求
/**
* 发送String格式的post请求
* @param url 请求地址,如:https://www.baidu.com/insterface
* @param headerMap 请求头,以map型式拼装
* @param param userId=111&name=777这种格式的字符串
* @return String
*/
public static String sendStringPost(String url, Map<String, String> headerMap, String param) {
// 创建httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost对象
HttpPost post = new HttpPost(url);
// 拼装Header
if (headerMap != null) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
post.setHeader(entry.getKey(), entry.getValue());
}
}
// 将map参数转成uri参数字符串格式
// String param = buildMap(map);
// 创建接收响应对象
CloseableHttpResponse response = null;
// 进行请求
try {
// 发送请求
post.setEntity(new StringEntity(param,"UTF-8"));
// 获取响应
response = httpClient.execute(post);
// 解析响应数据
if(response != null) {
// if(response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, "UTF-8");
}
} catch (IOException e) { // 处理异常
e.printStackTrace();
}finally {
try {
// 先关闭httpClient
httpClient.close();
// 再关闭response
if(response != null) response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}