326 lines
		
	
	
		
			12 KiB
		
	
	
	
		
			Java
		
	
	
	
			
		
		
	
	
			326 lines
		
	
	
		
			12 KiB
		
	
	
	
		
			Java
		
	
	
	
| package tqq9.lc123.cloud.app.plugin.utils;
 | ||
| 
 | ||
| import com.alibaba.fastjson.JSONArray;
 | ||
| import com.alibaba.fastjson.parser.Feature;
 | ||
| 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.HttpPost;
 | ||
| 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.slf4j.Logger;
 | ||
| import org.slf4j.LoggerFactory;
 | ||
| 
 | ||
| 
 | ||
| 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;
 | ||
| import java.nio.charset.StandardCharsets;
 | ||
| import java.util.List;
 | ||
| import java.util.Map;
 | ||
| import java.util.Set;
 | ||
| 
 | ||
| import com.alibaba.fastjson.JSONObject;
 | ||
| import org.dom4j.Document;
 | ||
| import org.dom4j.DocumentException;
 | ||
| import org.dom4j.DocumentHelper;
 | ||
| import org.dom4j.Element;
 | ||
| 
 | ||
| 
 | ||
| public class HttpRequestUtils {
 | ||
| 
 | ||
|     private static final Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);
 | ||
| 
 | ||
|     // 默认连接超时时间(毫秒)
 | ||
|     private static final int DEFAULT_CONNECT_TIMEOUT = 5000;
 | ||
|     // 默认请求超时时间(毫秒)
 | ||
|     private static final int DEFAULT_SOCKET_TIMEOUT = 10000;
 | ||
| 
 | ||
|     /**
 | ||
|      * 发送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; charset=UTF-8");
 | ||
|             httpPost.setHeader("Accept", "application/xml");
 | ||
|             if (headers != null && !headers.isEmpty()) {
 | ||
|                 headers.forEach(httpPost::setHeader);
 | ||
|             }
 | ||
| 
 | ||
|             // 设置请求体
 | ||
|             StringEntity entity = new StringEntity(xmlParams, ContentType.APPLICATION_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
 | ||
|      * @param jsonStr JSON字符串
 | ||
|      * @param escape 是否忽略特殊字符
 | ||
|      * @return XML字符串
 | ||
|      */
 | ||
|     public static String jsonToXml(String jsonStr, Boolean escape) {
 | ||
|         try {
 | ||
|             StringBuffer buffer = new StringBuffer();
 | ||
|             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();
 | ||
|     }
 | ||
| 
 | ||
| 
 | ||
| }
 |