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

  • 相关阅读:
    80后
    搞了 2 周性能优化,QPS 终于翻倍了!
    Spring Boot 实现各种参数校验,写得太好了,建议收藏!
    为什么编程语言社区没那么多初创公司呢?
    利用 Fastjson 注入 Spring 内存马,太秀了~!
    44 个神仙注释,太有才了……
    MySQL 中的 INSERT 是怎么加锁的?
    接了个变态需求:生成 Excel + PDF 导出,用 Java 怎么实现?
    重磅!Spring Boot 2.6 正式发布,一大波新特性,看完我彻底躺平了。。
    安装php xdebug扩展
  • 原文地址:https://www.cnblogs.com/qitian1/p/6461851.html
Copyright © 2011-2022 走看看