zoukankan      html  css  js  c++  java
  • SOAP消息创建

    看了SOAP消息分析之后,大家对soap消息应该有了一个初步的认识,那么怎样自己编写一个soap消息呢?
    先来创建一个简单的soap消息:

        @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();
            }
        }

    输出:

    <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中添加内容呢?

        @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();
            }
        }

    输出:

    <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消息的传递和处理。

  • 相关阅读:
    jsp_Scriptlet
    jsp_注释
    Http状态码详解
    Tomcat服务器的安装和配置
    【BZOJ 1018】线段树 **
    【BZOJ 2054】 2054: 疯狂的馒头 (并查集特技)
    【BZOJ 1969】 1969: [Ahoi2005]LANE 航线规划 (树链剖分+线段树)
    【BZOJ 1880】 [Sdoi2009]Elaxia的路线 (最短路树)
    【UOJ 79】 一般图最大匹配 (✿带花树开花)
    【UOJ 34】 多项式乘法 (FFT)
  • 原文地址:https://www.cnblogs.com/lenve/p/4517986.html
Copyright © 2011-2022 走看看