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

  • 相关阅读:
    2018
    线程的五大状态
    SQL 列转行与行转列
    python中元组(tuple)的拆包unkacping
    python字典的相关操作总结
    C语言使用typedef进行类型重定义
    C++中namespace的用法理解
    ping: unknown host 解决办法
    go环境变量配置liteide配置
    svn出现Authorization failed
  • 原文地址:https://www.cnblogs.com/qitian1/p/6461851.html
Copyright © 2020-2023  润新知