java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Springboot调用第三方WebService接口

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

作者: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接口内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文