springboot调用wsdl接口

springboot调用wsdl接口

  1. maven依赖
java 复制代码
	<!--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>
  1. 要求的入参出参示例
    入参:
xml 复制代码
<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>

出参:

xml 复制代码
<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>
  1. 代码实现
  • xml传参实体类
java 复制代码
@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;
    }
}
  • 参数传值
java 复制代码
导包路径:
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对象转换为XML
            StringWriter 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接口
java 复制代码
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();
    }
}
  1. 将xml格式响应报文解析为Json格式或者Map格式
java 复制代码
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则表示要构建list
	            if (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);
	            }
	        }
	    }
	}
}
  1. 将返回的xml数据保存到本地
java 复制代码
/**
* 保存返回的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();
    }
}
  1. 方法调用
java 复制代码
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);
       }
   }

}
相关推荐
Daniel 大东20 分钟前
BugJson因为json格式问题OOM怎么办
java·安全
Theodore_10224 小时前
4 设计模式原则之接口隔离原则
java·开发语言·设计模式·java-ee·接口隔离原则·javaee
冰帝海岸5 小时前
01-spring security认证笔记
java·笔记·spring
世间万物皆对象6 小时前
Spring Boot核心概念:日志管理
java·spring boot·单元测试
没书读了6 小时前
ssm框架-spring-spring声明式事务
java·数据库·spring
小二·6 小时前
java基础面试题笔记(基础篇)
java·笔记·python
开心工作室_kaic7 小时前
ssm161基于web的资源共享平台的共享与开发+jsp(论文+源码)_kaic
java·开发语言·前端
懒洋洋大魔王7 小时前
RocketMQ的使⽤
java·rocketmq·java-rocketmq
武子康7 小时前
Java-06 深入浅出 MyBatis - 一对一模型 SqlMapConfig 与 Mapper 详细讲解测试
java·开发语言·数据仓库·sql·mybatis·springboot·springcloud
qq_17448285757 小时前
springboot基于微信小程序的旧衣回收系统的设计与实现
spring boot·后端·微信小程序