Java(Sprigboot) 项目调用第三方 WebService 接口实现方式

devtools/2024/12/27 6:29:29/

文章目录

  • Java(Sprigboot) 项目调用第三方 WebService 接口实现方式
    • WebService 简介
    • 业务场景描述
    • WSDL 文档
      • 请求地址及方式
      • 接口请求/响应报文
    • 代码实现
      • 1、接口请求/响应报文 JSON 准备
        • (1)TransData
        • (2)BaseInfo、InputData、OutputData
          • BaseInfo
          • InputData
          • OutputData
      • 2、业务逻辑实现
        • (1)HttpClientBuilder 调用 WebService 接口实现
          • 1.引入 jar 包
          • 2.业务逻辑
        • (2)apache axis 方式调用
          • 1.引入依赖
          • 2.业务逻辑

Java(Sprigboot) 项目调用第三方 WebService 接口实现方式

WebService 简介

WebService 接口的发布通常一般都是使用 WSDL(web service descriptive language)文件的样式来发布的,该文档包含了请求的参数信息,返回的结果信息,我们需要根据 WSDL 文档的信息来编写相关的代码进行调用WebService接口。

业务场景描述

目前需要使用 java 调用一个WebService接口,传递参数的数据类型为 xml,返回的也是一个Xml的数据类型,需要实现调用接口,获取到xml 之后并解析为 Json 格式数据,并返回所需结果给前端。

WSDL 文档

请求地址及方式

接口地址请求方式
http://aabb.balabala.com.cn/services/BD?wsdlSOAP

接口请求/响应报文

<?xml version="1.0" encoding="UTF-8"?>
<TransData><BaseInfo><PrjID>BBB</PrjID>                  <UserID>UID</UserID>                                </BaseInfo><InputData><WriteType>220330</WriteType>   <HandCode>8</HandCode>                </InputData><OutputData><ResultCode>0</ResultCode>          <ResultMsg>获取权限编号成功!</ResultMsg>                            <OrgniseNo>SHUG98456</OrgniseNo> </OutputData>
</TransData>

代码实现

1、接口请求/响应报文 JSON 准备

首先准备好所需要的请求参数和返回数据的实体类

(1)TransData
java">import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = "TransData")
@XmlAccessorType(XmlAccessType.FIELD)
public class TransDataDto {@XmlElement(name = "BaseInfo")private BaseInfoDto baseInfo;@XmlElement(name = "InputData")private InputDataDto inputData;@XmlElement(name = "OutputData")private OutputDataDto outputData;public BaseInfoDto getBaseInfo() {return baseInfo;}public void setBaseInfo(BaseInfoDto baseInfo) {this.baseInfo = baseInfo;}public InputDataDto getInputData() {return inputData;}public void setInputData(InputDataDto inputData) {this.inputData = inputData;}public OutputDataDto getOutputData() {return outputData;}public void setOutputData(OutputDataDto outputData) {this.outputData = outputData;}}
(2)BaseInfo、InputData、OutputData
BaseInfo
java">import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = "BaseInfo")
@XmlAccessorType(XmlAccessType.FIELD)
public class BaseInfoDto {@XmlElement(name = "PrjID")private String prjId;@XmlElement(name = "UserID")private String userId;public String getPrjId() {return prjId;}public void setPrjId(String prjId) {this.prjId = prjId;}public String getUserId() {return userId;}public void setUserId(String userId) {this.userId = userId;}
}
InputData
java">import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = "InputData")
@XmlAccessorType(XmlAccessType.FIELD)
public class InputDataDto {@XmlElement(name = "WriteType")private String writeType;@XmlElement(name = "HandCode")private String handCode;public String getWriteType() {return writeType;}public void setWriteType(String writeType) {this.writeType = writeType;}public String getHandCode() {return handCode;}public void setHandCode(String handCode) {this.handCode = handCode;}
}
OutputData
java">import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name = "OutputData")
@XmlAccessorType(XmlAccessType.FIELD)
public class OutputDataDto {@XmlElement(name = "ResultCode")private String resultCode;@XmlElement(name = "ResultMsg")private String resultMsg;@XmlElement(name = "OrgniseNo")private String orgniseNo;public String getResultCode() {return resultCode;}public void setResultCode(String resultCode) {this.resultCode = resultCode;}public String getResultMsg() {return resultMsg;}public void setResultMsg(String resultMsg) {this.resultMsg = resultMsg;}public String getOrgniseNo() {return orgniseNo;}public void setOrgniseNo(String orgniseNo) {this.orgniseNo = orgniseNo;}
}

2、业务逻辑实现

(1)HttpClientBuilder 调用 WebService 接口实现
1.引入 jar 包
  			<!-- Jackson Core --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.15.0</version></dependency><!-- Jackson Databind --><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.15.0</version></dependency><!-- Jackson Dataformat XML --><dependency><groupId>com.fasterxml.jackson.dataformat</groupId><artifactId>jackson-dataformat-xml</artifactId><version>2.15.0</version></dependency>
2.业务逻辑
java">package com.ruoyi.system.service;import com.fasterxml.jackson.dataformat.xml.XmlMapper;import java.io.IOException;import com.fasterxml.jackson.core.JsonProcessingException;
import com.ruoyi.system.dto.soap.BaseInfoDto;
import com.ruoyi.system.dto.soap.InputDataDto;
import com.ruoyi.system.dto.soap.OutputDataDto;
import com.ruoyi.system.dto.soap.TransDataDto;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;import java.nio.charset.Charset;
import java.util.Objects;@Service
public class SoapTestService {private static final Logger log = LoggerFactory.getLogger(SoapTestService.class);public String getFinalValidNo(String wsdlUrl, String soapActon) {String finalValidNo = "";TransDataDto transDataDto = new TransDataDto();BaseInfoDto baseInfoDto = new BaseInfoDto();baseInfoDto.setPrjId("1");baseInfoDto.setUserId("1");InputDataDto inputDataDto = new InputDataDto();inputDataDto.setHandCode("1");inputDataDto.setWriteType("1");transDataDto.setBaseInfo(baseInfoDto);transDataDto.setInputData(inputDataDto);String soapParam = "";try {soapParam = transDataDtoToXmlStr(transDataDto);String soapResultStr = doSoapCall(wsdlUrl, soapParam, soapActon);TransDataDto transDataResponse = xmlToTransDataDto(soapResultStr);if (Objects.nonNull(transDataResponse)) {OutputDataDto outputDataDto = transDataDto.getOutputData();if (!"0".equals(outputDataDto.getResultCode())) {log.error("获取权限编号失败,详细信息:{}", outputDataDto.getResultMsg());throw new RuntimeException(outputDataDto.getResultMsg());}finalValidNo = outputDataDto.getOrgniseNo();}} catch (JsonProcessingException jp) {log.error("json 转 xml 异常,详细错误信息:{}", jp.getMessage());throw new RuntimeException(jp.getMessage());}return finalValidNo;}/*** @param wsdlUrl:wsdl   地址* @param soapParam:soap 请求参数* @param SoapAction* @return*/private String doSoapCall(String wsdlUrl, String soapParam, String SoapAction) {// 返回体String responseStr = "";// 创建HttpClientBuilderHttpClientBuilder httpClientBuilder = HttpClientBuilder.create();// HttpClientCloseableHttpClient closeableHttpClient = httpClientBuilder.build();HttpPost httpPost = new HttpPost(wsdlUrl);try {httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");httpPost.setHeader("SOAPAction", SoapAction);StringEntity data = new StringEntity(soapParam,Charset.forName("UTF-8"));httpPost.setEntity(data);CloseableHttpResponse response = closeableHttpClient.execute(httpPost);HttpEntity httpEntity = response.getEntity();if (httpEntity != null) {// 打印响应内容responseStr = EntityUtils.toString(httpEntity, "UTF-8");log.info("调用 soap 请求返回结果数据:{}", responseStr);}} catch (IOException e) {log.error("调用 soap 请求异常,详细错误信息:{}", e.getMessage());} finally {// 释放资源if (closeableHttpClient != null) {try {closeableHttpClient.close();} catch (IOException ioe) {log.error("释放资源失败,详细信息:{}", ioe.getMessage());}}}return responseStr;}/*** @param transDataDto* @return* @throws JsonProcessingException* @Des json 转 xml 字符串*/private String transDataDtoToXmlStr(TransDataDto transDataDto) throws JsonProcessingException {// 将 JSON 转换为 XML 字符串XmlMapper xmlMapper = new XmlMapper();StringBuilder stringBuilder = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");stringBuilder.append(xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(transDataDto));return stringBuilder.toString();}/*** @param xmlResponse* @return* @throws JsonProcessingException* @Des xml 转 json*/private TransDataDto xmlToTransDataDto(String xmlResponse) throws JsonProcessingException {// 将 XML 字符串转换为 Java 对象XmlMapper xmlMapper = new XmlMapper();TransDataDto transDataDto = xmlMapper.readValue(xmlResponse, TransDataDto.class);return transDataDto;}}
(2)apache axis 方式调用
1.引入依赖
    <dependency><groupId>org.apache.axis</groupId><artifactId>axis</artifactId><version>1.4</version></dependency>
2.业务逻辑
java">package com.ruoyi.system.service;import org.apache.axis.client.Call;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;import org.apache.axis.client.Service;import java.rmi.RemoteException;@Component
public class ApacheAxisTestService {private static final Logger log = LoggerFactory.getLogger(ApacheAxisTestService.class);public String sendWebService() {String requestXml = "";String soapResponseStr = "";String wsdlUrl = "";Service service = new Service();Object[] obj = new Object[1];obj[0] = requestXml;log.info("调用soap接口wsdl地址:{},请求参数:{}", wsdlUrl, requestXml);try {Call call = (Call) service.createCall();call.setTargetEndpointAddress(wsdlUrl);call.setTimeout(Integer.valueOf(30000));call.setOperation("doService");soapResponseStr = (String) call.invoke(obj);} catch (RemoteException r) {log.error("调用 soap 接口失败,详细错误信息:{}", r.getMessage());throw new RuntimeException(r.getMessage());}return soapResponseStr;}
}

注意!!!!!!!
如果现在开发WebService,用的大多是axis2或者CXF。

有时候三方给的接口例子中会用到标题上面的类,这个在axis2中是不存在,这两个类属于axis1中的!!!

在这里插入图片描述


http://www.ppmy.cn/devtools/145740.html

相关文章

Kafka无锁设计

前言 在分布式消息队列系统中,Kafka 的无锁设计是其高吞吐量和高并发的核心优势之一。通过避免锁的竞争,Kafka 能够在高并发和大规模的生产环境中保持高效的性能。为了更好地理解 Kafka 的无锁设计,我们首先对比传统的队列模型,然后探讨 Kafka 如何通过无锁机制优化生产者…

bash 中 ${-#*i} 是什么意思?

-------------------------------------------------- author: hjjdebug date: 2024年 12月 25日 星期三 17:43:45 CST description: bash 中 ${-#*i} 是什么意思? -------------------------------------------------- 在centos 的 /etc/profile 中有这样的语句 for i in /…

【算法题解】Bindian 山丘信号问题(E. Bindian Signaling)

问题描述 在 Berland 古老的 Bindian 部落中&#xff0c;首都被 nn 座山丘围成一个圆环&#xff0c;每个山丘上都有一名守望者&#xff0c;日夜观察着周围的情况。 如果有危险&#xff0c;守望者可以在山丘上点燃篝火。两座山丘的守望者可以看到彼此的信号&#xff0c;条件是…

只谈C++11新特性 - 默认函数

默认函数 C11之前的问题 在C11之前&#xff0c;如果给一个类显式地声明了构造函数&#xff08;无论是默认构造函数还是自定义的&#xff09;&#xff0c;系统就不会再生成默认的抽象赋值函数和拷贝构造函数。这带来了一些不方便和隐藏的问题。举一个简单的例子&#xff1a; …

2-196基于matlab的混沌改进蚁群算法优化PID

基于matlab的混沌改进蚁群算法优化PID。以控制误差为PID控制参数优化的目标函数&#xff0c;输入比例系数、积分比例系数、微分比例系数等参数进行优化&#xff0c;输出最佳的控制参数。程序已调通&#xff0c;可直接运行。 2-196基于matlab的混沌改进蚁群算法优化PID

无需公网 IP 实现外部访问 Puter 一站式云平台

Puter 是一款隐私至上的个人云&#xff0c;它是开源桌面环境&#xff0c;运行在浏览器中&#xff0c;这款桌面环境具备丰富的功能、异常快速和高度可扩展性。它可以用于构建远程桌面环境&#xff0c;也可以作为云存储服务、远程服务器、Web 托管平台等的界面。 第一步&#xf…

报表工具DevExpress Reporting v24.2亮点 - AI功能进一步强化

DevExpress Reporting是.NET Framework下功能完善的报表平台&#xff0c;它附带了易于使用的Visual Studio报表设计器和丰富的报表控件集&#xff0c;包括数据透视表、图表&#xff0c;因此您可以构建无与伦比、信息清晰的报表。 报表工具DevExpress Reporting v24.2将于近期发…

决策树(理论知识3)

目录 评选算法信息增益&#xff08; ID3 算法选用的评估标准&#xff09;信息增益率&#xff08; C4.5 算法选用的评估标准&#xff09;基尼系数&#xff08; CART 算法选用的评估标准&#xff09;基尼增益基尼增益率 评选算法 决策树学习的关键在于&#xff1a;如何选择最优划…