http工具类
package cn.sensorsdata.alarm_webhook.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.apache.http.HttpEntity;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.Map;
@Slf4j
public class HttpClientUtils {
private HttpClientUtils(){}
/**
* Http协议GET请求
*/
public static String httpGet(String url) throws IOException {
String result = null;
//初始化HttpClient
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients.createDefault();
//创建HttpGet
HttpGet httpGet = new HttpGet(url);
//发起请求,获取response对象
CloseableHttpResponse response = httpClient.execute(httpGet);
//获取返回数据实体对象
HttpEntity entity = response.getEntity();
//转为字符串
result = EntityUtils.toString(entity,"UTF-8");
}finally {
if(httpClient != null){
httpClient.close();
}
}
return result;
}
/**
* Http协议Post请求
*/
public static String httpPost (String url, Map<String,String> headers, String json) throws IOException{
String result = null;
//初始HttpClient
CloseableHttpClient httpClient = null;
try {
//初始HttpClient
httpClient = HttpClients.createDefault();
//创建Post对象
HttpPost httpPost = new HttpPost(url);
//设置Content-Type
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
//写入JSON数据
httpPost.setEntity(new StringEntity(json, Charsets.UTF_8));
//发起请求,获取response对象
CloseableHttpResponse response = httpClient.execute(httpPost);
//获取返回数据实体对象
HttpEntity entity = response.getEntity();
//转为字符串
result = EntityUtils.toString(entity, "UTF-8");
}finally {
if(httpClient != null){
httpClient.close();
}
}
return result;
}
}