【工具类】第三方接口调用实现,http请求工具类,包含xml请求和json请求

This commit is contained in:
tanfengling@x-ri.com 2025-09-10 14:54:02 +08:00
parent c3586aa8bc
commit 67c8f5f8d0
2 changed files with 361 additions and 0 deletions

View File

@ -0,0 +1,37 @@
package tqq9.lc123.cloud.app.plugin.trd;
import com.alibaba.fastjson.JSONObject;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import tqq9.lc123.cloud.app.plugin.utils.ConfigUtils;
import tqq9.lc123.cloud.app.plugin.utils.HttpRequestUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* 第三方接口调用
*/
public class TrdInterfaceImpl {
private static final Log logger = LogFactory.getLog(TrdInterfaceImpl.class);
//调用通天晓接口
public static JSONObject ttxImpl(String method, String param) throws IOException {
String ttx_customerId = ConfigUtils.getThirdConfigByNumber("Ttx_CustomerId");
String ttx_mainUrl = ConfigUtils.getThirdConfigByNumber("Ttx_MainURL");
Map<String, String> headers = new HashMap<>();
headers.put("method", method);
headers.put("v", "2.0");
headers.put("format", "xml");
headers.put("customerId", ttx_customerId);
String response = HttpRequestUtils.postXml(ttx_mainUrl, param, headers);
logger.info("ttx-responseXML" + response);
JSONObject resJSON = HttpRequestUtils.xmlToJson(response);
logger.info("ttx-responseJSON" + resJSON);
return resJSON;
}
}

View File

@ -0,0 +1,324 @@
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();
}
}