refactor(ic): 重构 HttpPostOtherSysImpl 类

- 替换 HttpURLConnection 为 Apache HttpClient 实现 HTTP 请求
- 优化获取 token 和发送请求的逻辑
- 添加日志记录功能
- 异常处理机制
This commit is contained in:
maolei 2025-05-16 14:44:12 +08:00
parent dc8a09b92e
commit ae51ee48cb
2 changed files with 121 additions and 141 deletions

View File

@ -1,18 +1,24 @@
package nccloud.pubift.commen.impl.utils;
import com.alibaba.fastjson.JSONObject;
import nccloud.pubift.commen.itf.utils.IHttpPostOtherSys;
import java.io.BufferedReader;
import com.alibaba.fastjson.JSONObject;
import nc.bs.logging.Log;
import nc.vo.pub.BusinessException;
import nccloud.pubift.commen.itf.utils.IHttpPostOtherSys;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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 java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpPostOtherSysImpl implements IHttpPostOtherSys {
private static final String USER_ID = "BIP";
@ -21,137 +27,131 @@ public class HttpPostOtherSysImpl implements IHttpPostOtherSys {
private static final String EP_ID = "";
private static final String LOGIN_URL = "/GTHINKING/AjaxService/N_MISPRO/100208057.ashx/Login";
private static final String LOG_INFO_NAME = "OALOG";
private static final Log obmlog = Log.getInstance(LOG_INFO_NAME);
@Override
public String callMes(String url, JSONObject json) {
// String leip = SysParaInitQuery.getParaString(PubEnv.getPk_group(), "LEIP");
String mesip = "http://192.168.29.32";
String baseurl = mesip + url;
String cookie = this.getMESToken(mesip);
String tokenValue = this.getMESToken(mesip);
Map<String, String> headers = new HashMap<>();
headers.put("Set-Cookie", cookie);
if (tokenValue != null) {
headers.put("Cookie", ".ASPXAUTH=" + tokenValue);
}
return doPost(baseurl, headers, json);
}
private String getMESToken(String leip) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("userId", USER_ID);
jsonObject.put("password", PASSWORD);
jsonObject.put("clientType", CLIENT_TYPE);
jsonObject.put("epId", EP_ID);
return postCookie(leip + LOGIN_URL, null, jsonObject);
/**
* 发送数据到外部系统
*/
public void sendToExternalSystem(String apiPath, Map<String, Object> requestData) throws BusinessException {
try {
obmlog.debug("HttpPostOtherSys request :" + JSONObject.toJSONString(requestData));
JSONObject jsonRequest = new JSONObject(requestData);
String response = callMes(apiPath, jsonRequest);
JSONObject jsonResponse = JSONObject.parseObject(response);
obmlog.debug("三方接口返回:" + jsonResponse.toJSONString());
String success = jsonResponse.getString("Success");
if ("false".equals(success)) {
String errorMessage = jsonResponse.getString("ErrorMessage");
if (errorMessage == null) {
errorMessage = "No error message provided by the external system.";
}
throw new BusinessException("同步mes系统失败,错误消息:" + errorMessage);
}
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException("调用外部接口失败:" + e.getMessage(), e);
}
}
/**
* ÒµÎñÇëÇópost·½·¨
*/
private String doPost(String baseurl, Map<String, String> map, JSONObject json) {
BufferedReader reader = null;
try {
URL url = new URL(baseurl);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST"); // 设置请求方式
// 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
if (map != null) {
for (String key : map.keySet()) {
connection.setRequestProperty(key, map.get(key));
}
}
connection.connect();
// 一定要用BufferedReader 来接收响应 使用字节来接收响应的方法是接收不到内容的
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // UTF-8编码
if (json != null) {
out.append(json.toString());
}
out.flush();
out.close();
// 读取响应
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
String res = "";
while ((line = reader.readLine()) != null) {
res += line;
}
reader.close();
return res;
} catch (Exception e) {
// e.printStackTrace();
throw new RuntimeException(e);
private String doPost(String baseurl, Map<String, String> headers, JSONObject jsonPayload) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(baseurl);
// Set standard headers
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
// Set custom headers from the map
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
/**
* 获取cookie的请求post
*/
private String postCookie(String baseurl, Map<String, String> map, JSONObject json) {
BufferedReader reader = null;
try {
URL url = new URL(baseurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
if (map != null) {
for (String key : map.keySet()) {
connection.setRequestProperty(key, map.get(key));
}
if (jsonPayload != null) {
StringEntity stringEntity = new StringEntity(jsonPayload.toJSONString(), "UTF-8");
httpPost.setEntity(stringEntity);
}
connection.connect();
// 写入请求体
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
if (json != null) {
out.append(json.toString());
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
return responseString;
}
out.flush();
out.close();
// 读取响应头中的 Set-Cookie
Map<String, List<String>> headers = connection.getHeaderFields();
String setCookieHeader = null;
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
if ("Set-Cookie".equalsIgnoreCase(entry.getKey())) {
setCookieHeader = entry.getValue().get(0); // 取第一个 Set-Cookie
break;
}
}
if (setCookieHeader != null) {
return extractAspxAuth(setCookieHeader); // 返回 ASPXAUTH 的值
} else {
return null;
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
// In a real application, use a proper logging framework
// e.printStackTrace();
throw new RuntimeException("HTTP POST request to " + baseurl + " failed: " + e.getMessage(), e);
}
}
// 提取 .ASPXAUTH 的值 - This method remains unchanged
private String extractAspxAuth(String setCookieHeaderLine) {
// setCookieHeaderLine 是一行完整的 Set-Cookie 响应头例如:
// ".ASPXAUTH=TOKEN_VALUE; path=/; HttpOnly"
// ".ASPXAUTH=TOKEN_VALUE;"
String[] cookieAttributes = setCookieHeaderLine.split(";"); // 按分号分割
for (String attribute : cookieAttributes) {
String trimmedAttribute = attribute.trim(); // 去除前后空格
if (trimmedAttribute.startsWith(".ASPXAUTH=")) {
return trimmedAttribute.substring(".ASPXAUTH=".length()); // 提取等号后的值
}
}
return null; // 没有找到 .ASPXAUTH
}
private String getMESToken(String mesIpBase) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("userId", USER_ID);
jsonObject.put("password", PASSWORD);
jsonObject.put("clientType", CLIENT_TYPE);
jsonObject.put("epId", EP_ID);
String loginUrl = mesIpBase + LOGIN_URL;
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost(loginUrl);
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity stringEntity = new StringEntity(jsonObject.toJSONString(), "UTF-8");
httpPost.setEntity(stringEntity);
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
Header[] setCookieHeaders = response.getHeaders("Set-Cookie");
if (setCookieHeaders != null) {
for (Header header : setCookieHeaders) {
String aspxAuthValue = extractAspxAuth(header.getValue());
if (aspxAuthValue != null) {
return aspxAuthValue; // Found and return .ASPXAUTH token value
}
}
}
// 提取 .ASPXAUTH 的值
private String extractAspxAuth(String cookieHeader) {
String[] cookies = cookieHeader.split("; ");
for (String cookie : cookies) {
if (cookie.startsWith(".ASPXAUTH=")) {
return cookie.substring(".ASPXAUTH=".length());
return null; // Return null if .ASPXAUTH cookie is not found, as per
}
} catch (IOException e) {
throw new RuntimeException("Failed to get MESToken (cookie) from " + loginUrl + " due to IO issue: " + e.getMessage(), e);
}
}
return null;
}
}

View File

@ -1,15 +1,19 @@
package nccloud.pubift.commen.itf.utils;
import com.alibaba.fastjson.JSONObject;
import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Log;
import nc.vo.pub.BusinessException;
import java.util.Iterator;
import java.util.Map;
public interface IHttpPostOtherSys {
String logginfo = "OALOG";
Log obmlog = Log.getInstance(logginfo);
/**
* @param apiPath MES的接口地址不包含ip
* @param json 入参
@ -19,30 +23,6 @@ public interface IHttpPostOtherSys {
/**
* 发送数据到外部系统
*/
default void sendToExternalSystem(String apiPaht, Map<String, Object> requestData) throws BusinessException {
try {
IHttpPostOtherSys httpService = NCLocator.getInstance().lookup(IHttpPostOtherSys.class);
JSONObject jsonRequest = new JSONObject(requestData);
String response = httpService.callMes(apiPaht, jsonRequest);
JSONObject jsonResponse = JSONObject.parseObject(response);
public void sendToExternalSystem(String apiPaht, Map<String, Object> requestData) throws BusinessException;
int code = jsonResponse.getIntValue("code");
if (code != 0) {
throw new Exception("自定义档案同步失败,错误码:" + code + ",消息:" + jsonResponse.getString("message"));
}
if (jsonResponse.containsKey("data") && !jsonResponse.getJSONObject("data").isEmpty()) {
JSONObject data = jsonResponse.getJSONObject("data");
StringBuilder errorMsg = new StringBuilder("自定义档案同步出现错误:");
Iterator<String> keys = data.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
errorMsg.append("\n编码 ").append(key).append(": ").append(data.get(key));
}
throw new Exception(errorMsg.toString());
}
} catch (Exception e) {
throw new BusinessException("调用外部接口失败:" + e.getMessage(), e);
}
}
}