首頁 >Java >java教程 >如何使用 SAAJ 在 Java 中實作 SOAP 用戶端?

如何使用 SAAJ 在 Java 中實作 SOAP 用戶端?

DDD
DDD原創
2024-11-09 03:07:02725瀏覽

How can I use SAAJ to implement a SOAP client in Java?

使用SAAJ 實作SOAP 客戶端

簡介

為了簡化SOAP 客戶端實現,Java 提供了SAAJ(Java 帶有附件的SOAP) Java API)框架。 SAAJ 支援直接操作 SOAP 請求和回應訊息。該框架是 JSE 1.6 和 11 及以上版本的一部分。

使用 SAAJ 的範例 SOAP 用戶端

以下 Java 程式碼片段展示了一個有效的 SOAP Web 服務呼叫使用SAAJ:

import javax.xml.soap.*;

public class SOAPClientSAAJ {

    // SAAJ - SOAP Client Testing
    public static void main(String[] args) {
        String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
        String soapAction = "http://www.webserviceX.NET/GetInfoByCity";

        callSoapWebService(soapEndpointUrl, soapAction);
    }

    private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
        String myNamespace = "myNamespace";
        String myNamespaceURI = "http://www.webserviceX.NET";

        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);

        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
        soapBodyElem1.addTextNode("New York");
    }

    private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
        try {
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection soapConnection = soapConnectionFactory.createConnection();

            SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);

            System.out.println("Response SOAP Message:");
            soapResponse.writeTo(System.out);
            System.out.println();

            soapConnection.close();
        } catch (Exception e) {
            System.err.println("Error occurred while sending SOAP Request to Server! Make sure you have the correct endpoint URL and SOAPAction!");
            e.printStackTrace();
        }
    }

    private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();

        createSoapEnvelope(soapMessage);

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", soapAction);

        soapMessage.saveChanges();

        System.out.println("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println("\n");

        return soapMessage;
    }
}

以上是如何使用 SAAJ 在 Java 中實作 SOAP 用戶端?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn