Java(Springboot)项目调用第三方WebService接口实现代码

 更新时间:2025年02月25日 10:17:14   作者:YD_1989  
这篇文章主要介绍了如何使用Java调用WebService接口,传递XML参数,获取XML响应,并将其解析为JSON格式,文中详细描述了WSDL文档的使用、HttpClientBuilder和Apache Axis两种调用方式的具体实现步骤,需要的朋友可以参考下

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 = "";
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient 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中的!!!

总结 

到此这篇关于Java(Springboot)项目调用第三方WebService接口实现代码的文章就介绍到这了,更多相关Springboot调用第三方WebService接口内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • spring结合struts的代码详解

    spring结合struts的代码详解

    这篇文章主要介绍了spring结合struts的代码详解,需要的朋友可以参考下
    2017-09-09
  • 基于Java生成GUID的实现方法

    基于Java生成GUID的实现方法

    本篇文章是对Java生成GUID的方法进行了详细的分析介绍,需要的朋友参考下
    2013-05-05
  • 解决idea中yml文件不识别的问题

    解决idea中yml文件不识别的问题

    这篇文章主要介绍了解决idea中yml文件不识别的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-01-01
  • Mybatis实现ResultMap结果集

    Mybatis实现ResultMap结果集

    本文主要介绍了Mybatis实现ResultMap结果集,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-04-04
  • Maven3种打包方式中maven-assembly-plugin的使用详解

    Maven3种打包方式中maven-assembly-plugin的使用详解

    这篇文章主要介绍了Maven3种打包方式中maven-assembly-plugin的使用,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-07-07
  • JNDI简介_动力节点Java学院整理

    JNDI简介_动力节点Java学院整理

    这篇文章主要介绍了JNDI简介,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • SpringData实现自定义Redis缓存的序列化机制和过期策略

    SpringData实现自定义Redis缓存的序列化机制和过期策略

    Spring Data Redis缓存通过提供灵活的配置选项,使开发者能够根据业务需求自定义序列化方式和过期策略,下面就来具体介绍一下,感兴趣的可以了解一下
    2025-04-04
  • Java虚拟机JVM优化实战的过程全记录

    Java虚拟机JVM优化实战的过程全记录

    有人说Java之所以能够崛起,JVM功不可没。Java虚拟机最初服务于让Java语言凌驾于平台之上,实现“编写一次,到处运行”,那么下面这篇文章主要给大家分享了个关于Java虚拟机JVM优化实战的过程全记录,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-08-08
  • Java Servlet中Response对象的使用方法

    Java Servlet中Response对象的使用方法

    本文介绍了Java Servlet中Response对象的使用方法,包括设置响应头、设置响应编码、向客户端发送数据、重定向等操作,同时介绍了常用的响应状态码和响应类型,帮助读者更好地理解和掌握Servlet中Response对象的用法
    2023-05-05
  • Java List<JSONObject>中的数据如何转换为List<T>

    Java List<JSONObject>中的数据如何转换为List<T>

    这篇文章主要介绍了Java List<JSONObject>中的数据如何转换为List<T>问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-05-05

最新评论