【工具类】http get请求方法

This commit is contained in:
tanfengling@x-ri.com 2025-09-11 10:27:02 +08:00
parent 813db84485
commit a890446817
2 changed files with 112 additions and 10 deletions

View File

@ -3,6 +3,7 @@ package tqq9.lc123.cloud.app.plugin.trd;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import kd.bos.logging.Log; import kd.bos.logging.Log;
import kd.bos.logging.LogFactory; import kd.bos.logging.LogFactory;
import org.apache.commons.lang3.StringUtils;
import tqq9.lc123.cloud.app.plugin.utils.ConfigUtils; import tqq9.lc123.cloud.app.plugin.utils.ConfigUtils;
import tqq9.lc123.cloud.app.plugin.utils.HttpRequestUtils; import tqq9.lc123.cloud.app.plugin.utils.HttpRequestUtils;
@ -30,8 +31,11 @@ public class TrdInterfaceImpl {
String response = HttpRequestUtils.postXml(ttx_mainUrl, param, headers); String response = HttpRequestUtils.postXml(ttx_mainUrl, param, headers);
logger.info("ttx-responseXML" + response); logger.info("ttx-responseXML" + response);
JSONObject resJSON = HttpRequestUtils.xmlToJson(response); if(StringUtils.isNotBlank(response)){
logger.info("ttx-responseJSON" + resJSON); JSONObject resJSON = HttpRequestUtils.xmlToJson(response);
return resJSON; logger.info("ttx-responseJSON" + resJSON);
return resJSON;
}
return null;
} }
} }

View File

@ -2,6 +2,8 @@ package tqq9.lc123.cloud.app.plugin.utils;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.Feature;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
@ -11,9 +13,8 @@ import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.slf4j.Logger; import org.apache.http.client.methods.HttpGet;
import org.slf4j.LoggerFactory; import org.apache.http.client.utils.URIBuilder;
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException; import javax.xml.bind.JAXBException;
@ -22,6 +23,7 @@ import javax.xml.bind.Unmarshaller;
import java.io.IOException; import java.io.IOException;
import java.io.StringReader; import java.io.StringReader;
import java.io.StringWriter; import java.io.StringWriter;
import java.net.URI;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -36,13 +38,109 @@ import org.dom4j.Element;
public class HttpRequestUtils { public class HttpRequestUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class); private static final Log logger = LogFactory.getLog(HttpRequestUtils.class);
// 默认连接超时时间毫秒 // 默认连接超时时间毫秒
private static final int DEFAULT_CONNECT_TIMEOUT = 5000; private static final int DEFAULT_CONNECT_TIMEOUT = 5000;
// 默认请求超时时间毫秒 // 默认请求超时时间毫秒
private static final int DEFAULT_SOCKET_TIMEOUT = 10000; private static final int DEFAULT_SOCKET_TIMEOUT = 10000;
/**
* 发送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, String> params,
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, String> params,
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, String> entry : params.entrySet()) {
builder.addParameter(entry.getKey(), entry.getValue());
}
}
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请求 * 发送JSON格式的POST请求
* @param url 请求URL * @param url 请求URL
@ -232,14 +330,14 @@ public class HttpRequestUtils {
/** /**
* 将JSON字符串转换为XML * 将JSON字符串转换为XML
* @param jsonStr JSON字符串 * @param json JSON对象
* @param escape 是否忽略特殊字符 * @param escape 是否忽略特殊字符
* @return XML字符串 * @return XML字符串
*/ */
public static String jsonToXml(String jsonStr, Boolean escape) { public static String jsonToXml(JSONObject json, Boolean escape) {
try { try {
StringBuffer buffer = new StringBuffer(); StringBuffer buffer = new StringBuffer();
JSONObject json = JSONObject.parseObject(jsonStr, Feature.OrderedField); // JSONObject json = JSONObject.parseObject(jsonStr, Feature.OrderedField);
jsonToXmlStr(json, buffer, escape != null && escape); jsonToXmlStr(json, buffer, escape != null && escape);
return buffer.toString(); return buffer.toString();
} catch (Exception e) { } catch (Exception e) {