springboot调用wsdl接口
- maven依赖
<!--xml报文数据--><dependency><groupId>com.fasterxml.jackson.dataformat</groupId><artifactId>jackson-dataformat-xml</artifactId><version>2.9.8</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web-services</artifactId></dependency><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-frontend-jaxws</artifactId><version>3.1.12</version></dependency><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-rt-transports-http</artifactId><version>3.1.12</version></dependency><!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api --><dependency><groupId>javax.xml.bind</groupId><artifactId>jaxb-api</artifactId><version>2.1</version></dependency><!-- https://mvnrepository.com/artifact/org.dom4j/dom4j --><dependency><groupId>org.dom4j</groupId><artifactId>dom4j</artifactId><version>2.1.4</version></dependency><!-- 需要指定JDK版本哦:2.4有13,15两个JDK版本 --><dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.4</version><classifier>jdk15</classifier></dependency><!-- https://mvnrepository.com/artifact/org.json/json --><dependency><groupId>org.json</groupId><artifactId>json</artifactId><version>20240303</version></dependency>
- 要求的入参出参示例
入参:
<InParam><PatientCode>310230198804141XXX</PatientCode><PatientCodeType>SH</PatientCodeType><VisitType /><VisitNo /><ReportType /><BeginTime>2020-08-16 00:00:01</BeginTime><EndTime>2021-08-16 23:59:59</EndTime>
</InParam>
出参:
<OutParam><ResultCode>1</ResultCode><ResultInfo>成功</ResultInfo><DataDetail><Report><ReportNo>A0001</ReportNo><ApplyOrderNo>112654</ApplyOrderNo><PatientNo>123456</PatientNo><VisitType>I</VisitType><VisitNo>111</VisitNo><SampleDesc>xxx</SampleDesc><ReportClass>01</ReportClass><ReportClassName>分类名称</ReportClassName><DrawDocCode>L1</DrawDocCode><DrawDocName>郭靖</DrawDocName><SampleTime>2016-03-13 09:00:00</SampleTime><ReciveDoc>L00168</ReciveDoc><ReciveDocName>黄蓉</ReciveDocName><ReciveTime>2016-03-13 09:10:00</ReciveTime><ReportDoc>L00178</ReportDoc><ReportDocName>欧阳修</ReportDocName><ReportTime>2016-03-13 09:10:00</ReportTime><BodySite/><ExamDept>1011</ExamDept><ExamDeptName>部门名称</ExamDeptName><VerifiDoc>L178</VerifiDoc><VerifiDocName>欧阳修</VerifiDocName><VerifiTime>2016-03-13 09:10:00</VerifiTime><Status>3</Status></Report>…</DataDetail>
</OutParam>
- 代码实现
- xml传参实体类
@XmlRootElement(name = "InParam")
public class RisReportDTO {private String PatientCode;private String PatientCodeType;private String VisitType;private String VisitNo;private String ReportType;private String BeginTime;private String EndTime;@XmlElement(name = "PatientCode", required = true)public String getPatientCode() {return PatientCode;}public void setPatientCode(String patientCode) {PatientCode = patientCode;}@XmlElement(name = "PatientCodeType", required = true)public String getPatientCodeType() {return PatientCodeType;}public void setPatientCodeType(String patientCodeType) {PatientCodeType = patientCodeType;}@XmlElement(name = "VisitType")public String getVisitType() {return VisitType;}public void setVisitType(String visitType) {VisitType = visitType;}@XmlElement(name = "VisitNo")public String getVisitNo() {return VisitNo;}public void setVisitNo(String visitNo) {VisitNo = visitNo;}@XmlElement(name = "ReportType")public String getReportType() {return ReportType;}public void setReportType(String reportType) {ReportType = reportType;}@XmlElement(name = "BeginTime", required = true)public String getBeginTime() {return BeginTime;}public void setBeginTime(String beginTime) {BeginTime = beginTime;}@XmlElement(name = "EndTime", required = true)public String getEndTime() {return EndTime;}public void setEndTime(String endTime) {EndTime = endTime;}
}
- 参数传值
导包路径:
import com.common.utils.xmlutils.XmlUtil;
import com.icu.dto.xmldto.RisReportDTO;
import com.icu.dto.xmldto.RisReportDetailsDTO;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.dom4j.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.*;
import java.util.*;public class ReportUtil {private static Logger logger = LoggerFactory.getLogger(ReportUtil.class);public static String getLisReportList(String hm, String lx, String startTime, String endTime) {RisReportDTO reportDTO = new RisReportDTO();reportDTO.setPatientCode(zjhm);reportDTO.setPatientCodeType(zjlx);if (StringUtils.isNotBlank(startTime)) {reportDTO.setBeginTime(startTime);}if (StringUtils.isNotBlank(endTime)) {reportDTO.setEndTime(endTime);}// 创建JAXB上下文JAXBContext jaxbContext = null;String xmlString = null;try {jaxbContext = JAXBContext.newInstance(RisReportDTO.class);// 创建Marshaller对象Marshaller marshaller = jaxbContext.createMarshaller();// 将Person对象转换为XMLStringWriter sw = new StringWriter();marshaller.marshal(reportDTO, sw);// 输出XML字符串xmlString = sw.toString();} catch (JAXBException e) {throw new RuntimeException(e);}// 发送检查报告列表String responseData = XmlUtil.sendWsdl(xmlString, "方法名称");return responseData;}
}
- 调用wsdl接口
import com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.cxf.endpoint.Client;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.util.*;public class XmlUtil {private static Logger logger = LoggerFactory.getLogger(XmlUtil.class);/*** 根据参数发送数据* @param xmlParam* @return*/public static String sendWsdl(String xmlParam, String method) {// 创建动态客户端JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();Client client = dcf.createClient("http://xxx.xxx.xxx.xxx:xxxx/services/XXXXXX?wsdl");// 将XML字符串作为单个参数传递Object[] params = new Object[]{xmlParam};Object[] objects = null;try {// invoke("方法名",参数1,参数2,参数3....);objects = client.invoke(method, params);logger.info("返回数据:" + objects[0]);} catch (java.lang.Exception e) {e.printStackTrace();}return objects[0].toString();}
}
- 将xml格式响应报文解析为Json格式或者Map格式
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.dom4j.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.*;
import java.util.*;public class XmlJson{/*** 将xml格式响应报文解析为Json格式* @param responseXmlTemp* @return*/public static String xml2Json(String responseXmlTemp) {Document doc = null;try {doc = DocumentHelper.parseText(responseXmlTemp);} catch (DocumentException e) {logger.error("parse text error : " + e);}Element rootElement = doc.getRootElement();Map<String,Object> mapXml = new HashMap<String,Object>();element2Map(mapXml,rootElement);String jsonXml = JSONObject.fromObject(mapXml).toString();return jsonXml;}/*** 将xml格式响应报文解析为Map格式* @param responseXmlTemp* @param* @return* @throws DocumentException*/public static Map<String, Object> xml2map(String responseXmlTemp) {Document doc = null;try {doc = DocumentHelper.parseText(responseXmlTemp);} catch (DocumentException e) {logger.error("parse text error : " + e);}Element rootElement = doc.getRootElement();Map<String,Object> mapXml = new HashMap<String,Object>();element2Map(mapXml,rootElement);System.out.println("Map >>> " + mapXml);return mapXml;}/*** 使用递归调用将多层级xml转为map* @param map* @param rootElement*/public static void element2Map(Map<String, Object> map, Element rootElement) {//获得当前节点的子节点List<Element> elements = rootElement.elements();if (elements.size() == 0) {//没有子节点说明当前节点是叶子节点,直接取值map.put(rootElement.getName(), rootElement.getText());} else if (elements.size() == 1) {//只有一个子节点说明不用考虑list的情况,继续递归Map<String, Object> tempMap = new HashMap<String, Object>();element2Map(tempMap, elements.get(0));map.put(rootElement.getName(), tempMap);} else {//多个子节点的话就要考虑list的情况了,特别是当多个子节点有名称相同的字段时Map<String, Object> tempMap = new HashMap<String, Object>();for (Element element : elements) {tempMap.put(element.getName(), null);}Set<String> keySet = tempMap.keySet();for (String string : keySet) {Namespace namespace = elements.get(0).getNamespace();List<Element> sameElements = rootElement.elements(new QName(string, namespace));//如果同名的数目大于1则表示要构建listif (sameElements.size() > 1) {List<Map> list = new ArrayList<Map>();for (Element element : sameElements) {Map<String, Object> sameTempMap = new HashMap<String, Object>();element2Map(sameTempMap, element);list.add(sameTempMap);}map.put(string, list);} else {//同名的数量不大于1直接递归Map<String, Object> sameTempMap = new HashMap<String, Object>();element2Map(sameTempMap, sameElements.get(0));map.put(string, sameTempMap);}}}}
}
- 将返回的xml数据保存到本地
/**
* 保存返回的xml数据到本地
* @param zjhm
* @param responseData 要保存的数据
* @param lxmc
*/
public void doSomethingAsync(String zjhm, String responseData, String lxmc) {// 这个方法将在新的线程中异步执行logger.info("信息");// 将返回结果保存在文件中,使用UTF-8编码将XML内容写入文件SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");String url = UrlConfig.getBaocunUrl() + "/baogao/" + sdf.format(new Date()) + "/" + zjhm + "/"+ lxmc +"/";if (!new File(url).exists()) {new File(url).mkdirs();}String filename = url + System.currentTimeMillis() + ".xml";if (!new File(filename).exists()) {try {new File(filename).createNewFile();} catch (IOException e) {throw new RuntimeException(e);}}try (FileOutputStream fos = new FileOutputStream(filename);OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8")) {osw.write(responseData);} catch (Exception e) {e.printStackTrace();}
}
- 方法调用
public R listReport() {String responseData = ReportUtil.getLisReportList(dto.getPatientID().getZjhm(), dto.getPatientID().getZjlx(), dto.getPatientID().getTimeDuration().getStart(), dto.getPatientID().getTimeDuration().getEnd());// 开启异步,保存文件doSomethingAsync(dto.getPatientID().getZjhm(), responseData, "jiancha");String string = ReportUtil.xml2Json(responseData);JSONObject jcReportJson = JSON.parseObject(string);JSONObject resultCodeJson = JSON.parseObject(jcReportJson.getString("ResultCode"));String resultCode = resultCodeJson.getString("ResultCode");if (resultCode.equals("1")) {String dataDetail = jcReportJson.getString("DataDetail");if (org.apache.commons.lang.StringUtils.isNotBlank(dataDetail)) {com.alibaba.fastjson.JSONObject dataDetailJson = JSON.parseObject(jcReportJson.getString("DataDetail"));String reportDetail = dataDetailJson.getString("Report");JSONArray jsonArray = new JSONArray(reportDetail);List<NodeVO> baogaoVoList = new ArrayList<>();for (int i = 0; i < jsonArray.length(); i++) {org.json.JSONObject jsonObject = jsonArray.getJSONObject(i);String reportNo = jsonObject.getJSONObject("ReportNo").getString("ReportNo");String reportName = jsonObject.getJSONObject("ReportName").getString("ReportName");String reportTime = jsonObject.getJSONObject("ReportTime").getString("ReportTime");// 这里是新建对象,用于保存数据,可根据自己需求进行修改/*NodeVO nodeVO = new NodeVO();nodeVO.setWybh(reportNo);nodeVO.setName(reportName);SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");try {nodeVO.setTime(sdf.parse(reportTime));} catch (ParseException e) {throw new RuntimeException(e);}nodeVO.setType("U09");baogaoVoList.add(nodeVO);*/}//nodeList.add(baogaoVoList);}}}