package com.gs.xiaomi.service; import com.gs.xiaomi.config.DataAcquisitionConfiguration; import com.gs.xiaomi.dto.BizDocumentResult; import com.gs.xiaomi.dto.ZfmWsApiRequest; import com.gs.xiaomi.util.SoapXmlBuilder; import com.gs.xiaomi.util.X5StringUtils; import okhttp3.*; import org.springframework.stereotype.Service; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import java.io.StringReader; import java.util.concurrent.TimeUnit; @Service public class SoapApiService { private final OkHttpClient client; public SoapApiService() { this.client = new OkHttpClient.Builder().connectTimeout(3000, TimeUnit.SECONDS) // Set connection timeout .readTimeout(90, TimeUnit.SECONDS) // Set read timeout .build(); } public BizDocumentResult callAndParse(String url, ZfmWsApiRequest request) throws Exception { String soapXml = SoapXmlBuilder.build(request); Response response = sendRequest(url, soapXml); if (response.isSuccessful() && response.body() != null) { String bodyStr = response.body().string(); String evCode = extractEvCode(bodyStr); if (!"Y".equalsIgnoreCase(evCode)) { throw new RuntimeException("SOAP business failed, EV_CODE: " + evCode); } String decodedXml = decodeXmlEntities(bodyStr); String innerXml = extractCdata(decodedXml); if (innerXml == null) throw new RuntimeException("No CDATA found in response"); JAXBContext context = JAXBContext.newInstance(BizDocumentResult.class); Unmarshaller unmarshaller = context.createUnmarshaller(); return (BizDocumentResult) unmarshaller.unmarshal(new StringReader(innerXml)); } else { throw new RuntimeException("SOAP request failed: " + response.code() + " - " + response.message()); } } private Response sendRequest(String url, String soapXml) throws Exception { MediaType mediaType = MediaType.parse("application/xml"); RequestBody body = RequestBody.create(mediaType, soapXml); String s = DataAcquisitionConfiguration.USER_NAME + ":" + DataAcquisitionConfiguration.PWD; String auth = X5StringUtils.encodeBase64(s); Request request = new Request.Builder() .url(url) .method("POST", body) .addHeader("Content-Type", "application/xml") .addHeader("Authorization", "Basic " + auth) .addHeader("Accept", "*/*") .addHeader("Connection", "keep-alive") .build(); return client.newCall(request).execute(); } private String extractEvCode(String xml) { int start = xml.indexOf(""); int end = xml.indexOf("", start); if (start == -1 || end == -1) return null; return xml.substring(start + 9, end).trim(); } private String decodeXmlEntities(String xml) { return xml.replace("<", "<") .replace(">", ">") .replace("<", "<") .replace(">", ">") .replace("&", "&"); } private String extractCdata(String xml) { int cdataStart = xml.indexOf(""); int cdataEnd = xml.indexOf("", cdataStart); if (cdataStart == -1 || cdataEnd == -1) return null; return xml.substring(cdataStart + 11, cdataEnd).trim(); } }