当前位置: 首页 > news >正文

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

文章目录

  • 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
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
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
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
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.业务逻辑
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.业务逻辑
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.mrgr.cn/news/81570.html

相关文章:

  • 作品分享:基于全志V3s核心板设计(MPCIE金手指设计)
  • 1.微服务灰度发布(方案设计)
  • Ubuntu网络配置(桥接模式, nat模式, host主机模式)
  • 【Spring】基于XML的Spring容器配置——<bean>标签与属性解析
  • 【物联网技术与应用】实验15:电位器传感器实验
  • 【MySQL】 SQL优化讲解
  • ViiTor实时翻译 2.2.1 | 完全免费的高识别率同声传译软件
  • 基于深度学习(HyperLPR3框架)的中文车牌识别系统-python程序开发测试
  • 如何使用命令行设置Java当前环境是最新版本的JDK
  • Leecode刷题C语言之字符串及其反转中是否存在同一子字符串
  • 电子应用设计方案73:智能家庭书柜系统设计
  • Android使用PorterDuffXfermode模式PorterDuff.Mode.SRC_OUT橡皮擦实现马赛克效果,Kotlin(3)
  • 代码随想录算法【Day2】
  • SpeedTree学习笔记总结
  • 概率论期末速成笔记(包过版)
  • k8s网络,跨主机容器通信机制(没看懂)
  • GitLab安装及使用
  • Llama 3 简介(一)
  • NVIDIA vGPU虚拟机显卡分片技术
  • uni-app 跨端开发精美开源UI框架推荐