lc/lc123/cloud/app/plugin/utils/HttpRequestUtils.java

481 lines
18 KiB
Java
Raw Normal View History

package tqq9.lc123.cloud.app.plugin.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
2025-09-11 02:27:02 +00:00
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
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.ContentType;
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 org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
2025-09-11 02:27:02 +00:00
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class HttpRequestUtils {
2025-09-11 02:27:02 +00:00
private static final Log logger = LogFactory.getLog(HttpRequestUtils.class);
// 默认连接超时时间(毫秒)
private static final int DEFAULT_CONNECT_TIMEOUT = 5000;
// 默认请求超时时间(毫秒)
private static final int DEFAULT_SOCKET_TIMEOUT = 10000;
2025-09-11 02:27:02 +00:00
/**
* 发送GET请求
* @param url 请求URL
* @return 响应字符串
* @throws IOException 请求异常时抛出
*/
public static String doGet(String url) throws IOException {
return doGet(url, null, null, DEFAULT_CONNECT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
}
/**
* 发送带参数和请求头的GET请求
* @param url 请求URL
* @param params 请求参数Map
* @param headers 请求头Map
* @return 响应字符串
* @throws IOException 请求异常时抛出
*/
public static String doGet(String url, Map<String, Object> params,
2025-09-11 02:27:02 +00:00
Map<String, String> headers) throws IOException {
return doGet(url, params, headers, DEFAULT_CONNECT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
}
/**
* 发送GET请求完整参数
* @param url 请求URL
* @param params 请求参数Map
* @param headers 请求头Map
* @param connectTimeout 连接超时时间(毫秒)
* @param socketTimeout 请求超时时间(毫秒)
* @return 响应字符串
* @throws IOException 请求异常时抛出
*/
public static String doGet(String url, Map<String, Object> params,
2025-09-11 02:27:02 +00:00
Map<String, String> headers,
int connectTimeout, int socketTimeout) throws IOException {
// 创建HttpClient实例
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 构建URI
URIBuilder builder = new URIBuilder(url);
// 添加请求参数
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
builder.addParameter(entry.getKey(), entry.getValue().toString());
2025-09-11 02:27:02 +00:00
}
}
URI uri = builder.build();
// 创建GET请求
HttpGet httpGet = new HttpGet(uri);
// 设置请求配置(超时时间)
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.build();
httpGet.setConfig(config);
// 添加请求头
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
}
logger.debug("Sending GET request to: {}", uri);
// 执行请求并处理响应
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (entity == null) {
throw new IOException("Empty response entity");
}
String responseBody = EntityUtils.toString(entity, "UTF-8");
logger.debug("Response status: {}, Body: {}", statusCode, responseBody);
if (statusCode < 200 || statusCode >= 300) {
throw new IOException("HTTP request failed with status code: " + statusCode);
}
return responseBody;
}
} catch (Exception e) {
logger.error("GET request failed: {}", e.getMessage());
throw new IOException("GET request failed", e);
}
}
/**
* 发送JSON格式的POST请求
* @param url 请求URL
* @param jsonParams JSON参数字符串
* @param headers 请求头Map
* @return 响应字符串
* @throws IOException 请求异常时抛出
*/
public static String postJson(String url, String jsonParams, Map<String, String> headers) throws IOException {
return postJson(url, jsonParams, headers, DEFAULT_CONNECT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
}
/**
* 发送JSON格式的POST请求带超时配置
* @param url 请求URL
* @param jsonParams JSON参数字符串
* @param headers 请求头Map
* @param connectTimeout 连接超时时间毫秒
* @param socketTimeout 请求超时时间毫秒
* @return 响应字符串
* @throws IOException 请求异常时抛出
*/
public static String postJson(String url, String jsonParams, Map<String, String> headers,
int connectTimeout, int socketTimeout) throws IOException {
// 创建HttpClient实例
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 创建POST请求
HttpPost httpPost = new HttpPost(url);
// 设置请求配置(超时时间)
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.build();
httpPost.setConfig(config);
// 设置请求头
httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
httpPost.setHeader("Accept", "application/json");
if (headers != null && !headers.isEmpty()) {
headers.forEach(httpPost::setHeader);
}
// 设置请求体
StringEntity entity = new StringEntity(jsonParams, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行请求并处理响应
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity responseEntity = response.getEntity();
if (responseEntity == null) {
throw new IOException("Empty response entity");
}
String responseBody = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
logger.debug("Response status: {}, Body: {}", statusCode, responseBody);
if (statusCode < 200 || statusCode >= 300) {
throw new IOException("HTTP request failed with status code: " + statusCode);
}
return responseBody;
}
}
}
/**
* 发送XML格式的POST请求
* @param url 请求URL
* @param xmlParams XML参数字符串
* @param headers 请求头Map
* @return 响应字符串
* @throws IOException 请求异常时抛出
*/
public static String postXml(String url, String xmlParams, Map<String, String> headers) throws IOException {
return postXml(url, xmlParams, headers, DEFAULT_CONNECT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
}
/**
* 发送XML格式的POST请求带超时配置
* @param url 请求URL
* @param xmlParams XML参数字符串
* @param headers 请求头Map
* @param connectTimeout 连接超时时间毫秒
* @param socketTimeout 请求超时时间毫秒
* @return 响应字符串
* @throws IOException 请求异常时抛出
*/
public static String postXml(String url, String xmlParams, Map<String, String> headers,
int connectTimeout, int socketTimeout) throws IOException {
// 创建HttpClient实例
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 创建POST请求
HttpPost httpPost = new HttpPost(url);
// 设置请求配置(超时时间)
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setSocketTimeout(socketTimeout)
.build();
httpPost.setConfig(config);
// 设置请求头
// httpPost.setHeader("Content-Type", "application/xml");
// httpPost.setHeader("Accept", "application/xml");
if (headers != null && !headers.isEmpty()) {
headers.forEach(httpPost::setHeader);
}
// 设置请求体
StringEntity entity = new StringEntity(xmlParams, ContentType.APPLICATION_SOAP_XML);
httpPost.setEntity(entity);
// 执行请求并处理响应
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity responseEntity = response.getEntity();
if (responseEntity == null) {
throw new IOException("Empty response entity");
}
String responseBody = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
logger.debug("Response status: {}, Body: {}", statusCode, responseBody);
if (statusCode < 200 || statusCode >= 300) {
throw new IOException("HTTP request failed with status code: " + statusCode);
}
return responseBody;
}
}
}
/**
* 将XML字符串转换为Fastjson的JSONObject
* @param xml XML字符串
* @return JSONObject对象
*/
public static JSONObject xmlToJson(String xml) {
JSONObject jsonObject = new JSONObject();
try {
Document document = DocumentHelper.parseText(xml);
Element root = document.getRootElement();
iterateNodes(root, jsonObject);
} catch (DocumentException e) {
e.printStackTrace();
}
return jsonObject;
}
private static void iterateNodes(Element node, JSONObject json) {
String nodeName = node.getName();
List<Element> listElement = node.elements();
if (listElement.isEmpty()) {
json.put(nodeName, node.getTextTrim());
} else {
if (json.containsKey(nodeName)) {
Object o = json.get(nodeName);
JSONArray array;
if (o instanceof JSONArray) {
array = (JSONArray) o;
} else {
array = new JSONArray();
array.add(o);
}
JSONObject newJson = new JSONObject();
for (Element e : listElement) {
iterateNodes(e, newJson);
}
array.add(newJson);
json.put(nodeName, array);
} else {
JSONObject newJson = new JSONObject();
for (Element e : listElement) {
iterateNodes(e, newJson);
}
json.put(nodeName, newJson);
}
}
}
/**
* 将JSON字符串转换为XML
2025-09-11 02:27:02 +00:00
* @param json JSON对象
* @param escape 是否忽略特殊字符
* @return XML字符串
*/
2025-09-11 02:27:02 +00:00
public static String jsonToXml(JSONObject json, Boolean escape) {
try {
StringBuffer buffer = new StringBuffer();
2025-09-11 02:27:02 +00:00
// JSONObject json = JSONObject.parseObject(jsonStr, Feature.OrderedField);
jsonToXmlStr(json, buffer, escape != null && escape);
return buffer.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
private static void jsonToXmlStr(JSONObject json, StringBuffer buffer, boolean escape) {
Set<String> keySet = json.keySet();
for (String key : keySet) {
Object value = json.get(key);
if (escape) {
buffer.append("<").append(key).append("><![CDATA[");
} else {
buffer.append("<").append(key).append(">");
}
if (value instanceof JSONObject) {
jsonToXmlStr((JSONObject) value, buffer, escape);
} else if (value instanceof JSONArray) {
JSONArray array = (JSONArray) value;
for (Object obj : array) {
if (obj instanceof JSONObject) {
jsonToXmlStr((JSONObject) obj, buffer, escape);
} else {
buffer.append(obj.toString());
}
}
} else {
buffer.append(value.toString());
}
if (escape) {
buffer.append("]]></").append(key).append(">");
} else {
buffer.append("</").append(key).append(">");
}
}
}
/**
* 将Java对象转换为XML字符串
* @param obj 要转换的对象
* @return XML字符串
* @throws JAXBException 转换异常时抛出
*/
public static <T> String convertObjectToXml(T obj) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
return writer.toString();
}
/**
* 将XML字符串转换为Java对象
* @param xml XML字符串
* @param clazz 目标类
* @return Java对象
* @throws JAXBException 转换异常时抛出
*/
public static <T> T convertXmlToObject(String xml, Class<T> clazz) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = context.createUnmarshaller();
StringReader reader = new StringReader(xml);
return clazz.cast(unmarshaller.unmarshal(reader));
}
/**
* 使用Gson将Java对象转换为JSON字符串
* @param obj 要转换的对象
* @return JSON字符串
*/
public static String convertObjectToJson(Object obj) {
// 实际项目中可以使用Gson或Jackson等JSON库
// 这里简化实现实际使用时请替换为具体JSON库的实现
return obj.toString();
}
2025-10-27 07:30:18 +00:00
public static void buildXml(StringBuilder xmlBuilder, Map<String, Object> map, int indent) {
String indentStr = createIndent(indent);
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value instanceof Map) {
// 处理嵌套Map
xmlBuilder.append(indentStr).append("<").append(key).append(">\n");
buildXml(xmlBuilder, (Map<String, Object>) value, indent + 1);
xmlBuilder.append(indentStr).append("</").append(key).append(">\n");
} else if (value instanceof List) {
// 处理List
List<?> list = (List<?>) value;
for (Object item : list) {
if (item instanceof Map) {
xmlBuilder.append(indentStr).append("<").append(key).append(">\n");
buildXml(xmlBuilder, (Map<String, Object>) item, indent + 1);
xmlBuilder.append(indentStr).append("</").append(key).append(">\n");
} else {
xmlBuilder.append(indentStr).append("<").append(key).append(">")
.append(escapeXml(item.toString()))
.append("</").append(key).append(">\n");
}
}
} else {
// 处理普通值
if (value == null) {
xmlBuilder.append(indentStr).append("<").append(key).append("/>\n");
} else {
xmlBuilder.append(indentStr).append("<").append(key).append(">")
.append(escapeXml(value.toString()))
.append("</").append(key).append(">\n");
}
}
}
}
/**
* XML特殊字符转义
*/
public static String escapeXml(String text) {
if (text == null) return "";
return text.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
.replace("'", "&apos;");
}
// 自定义缩进方法
public static String createIndent(int indent) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < indent; i++) {
sb.append(" "); // 4个空格
}
return sb.toString();
}
}