SOAP消息建立

看了SOAP消息分析以後,你們對soap消息應該有了一個初步的認識,那麼怎樣本身編寫一個soap消息呢?
先來建立一個簡單的soap消息:ruby

@Test
    public void test1(){
        try {
            //1.建立消息工廠
            MessageFactory factory = MessageFactory.newInstance();
            //2.根據消息工廠建立SoapMessage
            SOAPMessage message = factory.createMessage();
            //3.建立SOAPPart
            SOAPPart part = message.getSOAPPart();
            //4.獲取SOAPEnvelope
            SOAPEnvelope envelope = part.getEnvelope();
            //5.能夠經過信封有效的獲取header和body的內容
            SOAPBody body = envelope.getBody();
            //6.根據QName建立相應的節點,QName是帶有命名空間的節點
            //這裏是建立一個<lenve:add xmlns="http://www.lenve.test">
            QName qname = new QName("http://www.lenve.test", "add", "lenve");
            body.addBodyElement(qname);
            message.writeTo(System.out);
        } catch (SOAPException | IOException e) {
            e.printStackTrace();
        }
    }

輸出:tcp

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/><SOAP-ENV:Body><lenve:add xmlns:lenve="http://www.lenve.test"/></SOAP-ENV:Body></SOAP-ENV:Envelope>

和咱們在上一篇中用tcpmon捕獲的消息一致,沒問題。但是這個body裏邊是空的,那麼怎樣給body中添加內容呢?ide

@Test
    public void test2(){
        try {
            MessageFactory factory = MessageFactory.newInstance();
            SOAPMessage message = factory.createMessage();
            SOAPPart part = message.getSOAPPart();
            SOAPEnvelope envelope = part.getEnvelope();
            SOAPBody body = envelope.getBody();
            QName qname = new QName("http://www.lenve.test", "add", "lenve");
            SOAPBodyElement element = body.addBodyElement(qname);
            element.addChildElement("a").setValue("3");
            element.addChildElement("b").setValue("4");
            message.writeTo(System.out);
        } catch (SOAPException | IOException e) {
            e.printStackTrace();
        }
    }

輸出:spa

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/><SOAP-ENV:Body><lenve:add xmlns:lenve="http://www.lenve.test"><a>3</a><b>4</b></lenve:add></SOAP-ENV:Body></SOAP-ENV:Envelope>
<a>3</a><b>4</b>都已經順利添加進去了。

下一篇看soap消息的傳遞和處理。code

相關文章
相關標籤/搜索