package com.ruoyi.common.utils.http;
|
|
import java.io.BufferedReader;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.io.InputStreamReader;
|
import java.nio.charset.StandardCharsets;
|
import javax.servlet.ServletRequest;
|
import org.apache.commons.lang3.exception.ExceptionUtils;
|
import org.apache.http.HttpResponse;
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
import org.apache.http.client.methods.HttpGet;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.HttpClients;
|
import org.apache.http.util.EntityUtils;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
|
/**
|
* 通用http工具封装
|
*
|
* @author ruoyi
|
*/
|
public class HttpHelper
|
{
|
private static final Logger LOGGER = LoggerFactory.getLogger(HttpHelper.class);
|
|
public static String getBodyString(ServletRequest request)
|
{
|
StringBuilder sb = new StringBuilder();
|
BufferedReader reader = null;
|
try (InputStream inputStream = request.getInputStream())
|
{
|
reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
|
String line = "";
|
while ((line = reader.readLine()) != null)
|
{
|
sb.append(line);
|
}
|
}
|
catch (IOException e)
|
{
|
LOGGER.warn("getBodyString出现问题!");
|
}
|
finally
|
{
|
if (reader != null)
|
{
|
try
|
{
|
reader.close();
|
}
|
catch (IOException e)
|
{
|
LOGGER.error(ExceptionUtils.getMessage(e));
|
}
|
}
|
}
|
return sb.toString();
|
}
|
|
/**
|
* 执行HTTP GET请求并返回响应内容
|
* @param url 请求的URL
|
* @param headers 请求头数组
|
* @return 响应内容字符串
|
*/
|
public static String httpGet(String url, org.apache.http.Header[] headers) {
|
CloseableHttpClient httpClient = HttpClients.createDefault();
|
HttpGet httpGet = new HttpGet(url);
|
|
// 设置请求头
|
if (headers != null) {
|
for (org.apache.http.Header header : headers) {
|
httpGet.setHeader(header);
|
}
|
}
|
|
try {
|
CloseableHttpResponse response = httpClient.execute(httpGet);
|
return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
|
} catch (IOException e) {
|
LOGGER.error("执行HTTP GET请求时发生错误:{}", e.getMessage());
|
return null;
|
} finally {
|
try {
|
httpClient.close();
|
} catch (IOException e) {
|
LOGGER.error("关闭HTTP客户端时发生错误:{}", e.getMessage());
|
}
|
}
|
}
|
}
|