最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java(Springboot)項目調用第三方WebService接口實現(xiàn)代碼

 更新時間:2025年02月25日 10:17:14   作者:YD_1989  
這篇文章主要介紹了如何使用Java調用WebService接口,傳遞XML參數(shù),獲取XML響應,并將其解析為JSON格式,文中詳細描述了WSDL文檔的使用、HttpClientBuilder和Apache?Axis兩種調用方式的具體實現(xiàn)步驟,需要的朋友可以參考下

WebService 簡介

WebService 接口的發(fā)布通常一般都是使用 WSDL(web service descriptive language)文件的樣式來發(fā)布的,該文檔包含了請求的參數(shù)信息,返回的結果信息,我們需要根據(jù) WSDL 文檔的信息來編寫相關的代碼進行調用WebService接口。

業(yè)務場景描述

目前需要使用 java 調用一個WebService接口,傳遞參數(shù)的數(shù)據(jù)類型為 xml,返回的也是一個Xml的數(shù)據(jù)類型,需要實現(xiàn)調用接口,獲取到xml 之后并解析為 Json 格式數(shù)據(jù),并返回所需結果給前端。

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>

代碼實現(xiàn)

1、接口請求/響應報文 JSON 準備

首先準備好所需要的請求參數(shù)和返回數(shù)據(jù)的實體類

(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、業(yè)務邏輯實現(xiàn)

(1)HttpClientBuilder 調用 WebService 接口實現(xiàn)

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.業(yè)務邏輯

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 請求參數(shù)
     * @param SoapAction
     * @return
     */
    private String doSoapCall(String wsdlUrl, String soapParam, String SoapAction) {
        // 返回體
        String responseStr = "";
        // 創(chuàng)建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 請求返回結果數(shù)據(jù):{}", 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.業(yè)務邏輯

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地址:{},請求參數(shù):{}", 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;
    }
}

注意!?。。。。?!如果現(xiàn)在開發(fā)WebService,用的大多是axis2或者CXF。

有時候三方給的接口例子中會用到標題上面的類,這個在axis2中是不存在,這兩個類屬于axis1中的?。?!

總結 

到此這篇關于Java(Springboot)項目調用第三方WebService接口實現(xiàn)代碼的文章就介紹到這了,更多相關Springboot調用第三方WebService接口內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • spring結合struts的代碼詳解

    spring結合struts的代碼詳解

    這篇文章主要介紹了spring結合struts的代碼詳解,需要的朋友可以參考下
    2017-09-09
  • 基于Java生成GUID的實現(xiàn)方法

    基于Java生成GUID的實現(xiàn)方法

    本篇文章是對Java生成GUID的方法進行了詳細的分析介紹,需要的朋友參考下
    2013-05-05
  • 解決idea中yml文件不識別的問題

    解決idea中yml文件不識別的問題

    這篇文章主要介紹了解決idea中yml文件不識別的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-01-01
  • Mybatis實現(xiàn)ResultMap結果集

    Mybatis實現(xiàn)ResultMap結果集

    本文主要介紹了Mybatis實現(xiàn)ResultMap結果集,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-04-04
  • Maven3種打包方式中maven-assembly-plugin的使用詳解

    Maven3種打包方式中maven-assembly-plugin的使用詳解

    這篇文章主要介紹了Maven3種打包方式中maven-assembly-plugin的使用,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-07-07
  • JNDI簡介_動力節(jié)點Java學院整理

    JNDI簡介_動力節(jié)點Java學院整理

    這篇文章主要介紹了JNDI簡介,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-08-08
  • SpringData實現(xiàn)自定義Redis緩存的序列化機制和過期策略

    SpringData實現(xiàn)自定義Redis緩存的序列化機制和過期策略

    Spring Data Redis緩存通過提供靈活的配置選項,使開發(fā)者能夠根據(jù)業(yè)務需求自定義序列化方式和過期策略,下面就來具體介紹一下,感興趣的可以了解一下
    2025-04-04
  • Java虛擬機JVM優(yōu)化實戰(zhàn)的過程全記錄

    Java虛擬機JVM優(yōu)化實戰(zhàn)的過程全記錄

    有人說Java之所以能夠崛起,JVM功不可沒。Java虛擬機最初服務于讓Java語言凌駕于平臺之上,實現(xiàn)“編寫一次,到處運行”,那么下面這篇文章主要給大家分享了個關于Java虛擬機JVM優(yōu)化實戰(zhàn)的過程全記錄,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-08-08
  • Java Servlet中Response對象的使用方法

    Java Servlet中Response對象的使用方法

    本文介紹了Java Servlet中Response對象的使用方法,包括設置響應頭、設置響應編碼、向客戶端發(fā)送數(shù)據(jù)、重定向等操作,同時介紹了常用的響應狀態(tài)碼和響應類型,幫助讀者更好地理解和掌握Servlet中Response對象的用法
    2023-05-05
  • Java?List<JSONObject>中的數(shù)據(jù)如何轉換為List<T>

    Java?List<JSONObject>中的數(shù)據(jù)如何轉換為List<T>

    這篇文章主要介紹了Java?List<JSONObject>中的數(shù)據(jù)如何轉換為List<T>問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-05-05

最新評論

同心县| 灌南县| 偏关县| 杭锦旗| 巍山| 子洲县| 城口县| 阿荣旗| 荣昌县| 长治县| 务川| 苏州市| 宣汉县| 紫云| 阿拉善左旗| 衡阳县| 南岸区| 东台市| 枣阳市| 无棣县| 崇信县| 上饶市| 沙河市| 宜黄县| 余干县| 莲花县| 孟津县| 临海市| 项城市| 崇明县| 庆安县| 镇安县| 鄂温| 云安县| 区。| 白玉县| SHOW| 阿克| 定南县| 革吉县| 梨树县|