soap类型的xml报文如何使用Java生成?

1、什么是soap?

英文全称:Simple Object Access Protocol,简单对象访问协议是交换数据的一种协议规范,是一种轻量的、简单的、基于XML标准通用标记语言下的一个子集)的协议,它被设计成在WEB上交换结构化的和固化的信息。

 

2、SOAP消息格式:
1
2
3
4
5
6
7
8
<SOAP-ENV:Envelope
 各种属性>
<!--百度百科示例-->
 <SOAP:HEADER>
 </SOAP:HEADER>
 <SOAP:Body>
 </SOAP:Body>
</SOAP-ENV:Envelope>
主要在web服务中运用。

 

3、语法规则

构建模块

一条 SOAP 消息就是一个普通的 XML 文档,包含下列元素:
  • 必需的 Envelope 元素,可把此 XML 文档标识为一条 SOAP 消息
  • 可选的 Header 元素,包含头部信息
  • 必需的 Body 元素,包含所有的调用和响应信息
  • 可选的 Fault 元素,提供有关在处理此消息所发生错误的信息
这里是一些重要的语法规则:
  • SOAP 消息必须用 XML 来编码
  • SOAP 消息必须使用 SOAP Envelope 命名空间
  • SOAP 消息必须使用 SOAP Encoding 命名空间
  • SOAP 消息不能包含 DTD 引用
  • SOAP 消息不能包含 XML 处理指令

消息基本结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml
 version="1.0"?>
<soap:Envelope
 
<soap:Header>
<!--百度百科示例-->
</soap:Header>
 
<soap:Body>
<!--百度百科示例-->
<soap:Fault>
<!--百度百科示例-->
</soap:Fault>
</soap:Body>
</soap:Envelope>

4、案例分享

 

代码

package com.xc.soap;

import java.util.ArrayList;
import java.util.List;
import javax.swing.text.Document;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Node;
import org.xml.sax.InputSource;

public class SOAPUtil {
    
    public static void main(String[] args) throws Exception {
        //创建本类的对象
        SOAPUtil util = new SOAPUtil();
        //调用本类的方法
        SOAPPart part = util.initsoappart();
        //获取返回的soap报文
        Source inform = util.getparametervalues(part, util.getTestNames());
        //输出这些soap报文到控制台,如果是我,我只需要封装就行了
        util.soap2string(inform);
    }

    /*
     * 总结:
     * 1、既然有set元素,那么就可以进行get元素中的内容
     */
    
    /**
     * 封装命名空间、请求头
     * @return
     * @throws SOAPException
     */
    public SOAPPart initsoappart() throws SOAPException {
        //创建SoapMessage
        SOAPMessage soapmessage = MessageFactory.newInstance().createMessage();
        //创建SoapPart
        SOAPPart soappart = soapmessage.getSOAPPart();
        //创建SoapEnvelope
        SOAPEnvelope soapenvelope = soappart.getEnvelope();
        //创建Header
        SOAPHeader soapheader = soapenvelope.getHeader();
        //创建命名空间声明
        
        //实际的报文输出:SOAP-ENV、cwmp、soap-enc、xsd、xsi
        //维度没有第一个?说明第一个是默认的
        SOAPElement cwmp = soapenvelope.addNamespaceDeclaration("cwmp",
                "urn:dslforum-org:cwmp-1-0");
        SOAPElement xsi = soapenvelope.addNamespaceDeclaration("xsi",
                "http://www.w3.org/2001/xmlschema-instance");
        SOAPElement xsd = soapenvelope.addNamespaceDeclaration("xsd",
                "http://www.w3.org/2001/xmlschema");

        SOAPElement enc = soapenvelope.addNamespaceDeclaration("soap-enc",
                "http://schemas.xmlsoap.org/soap/encoding/");

        //向soap头中添加数据
        SOAPElement id = soapheader.addChildElement("id", "cwmp");//也就是说在header中新增子标签
        //向标签中添加数据
        id.setTextContent("1");
        //返回SOAPPart对象
        return soappart;
    }
    
    
    
    /**
     * 封装请求体内容
     * @param part
     * @param list
     * @return
     * @throws Exception
     */
    public Source getparametervalues(SOAPPart part, @SuppressWarnings("rawtypes") List list) throws Exception {
        //再次通过soappart对象创建envelope对象
        SOAPEnvelope soapenvelope = part.getEnvelope();
        //通过envelope对象获取body对象
        SOAPBody soapbody = soapenvelope.getBody();
        //通过body对象创建子节点  <cwmp:getparametervalues>
        SOAPElement informres = soapbody.addChildElement("getparametervalues",
                "cwmp");
        @SuppressWarnings("static-access")
        //实例化SOAP工厂
        SOAPFactory soapfactory = SOAPFactory.newInstance();
        //通过soap工厂创建标签  <parameternames soap-enc:arraytype="xsd:string[27]">
        SOAPElement names = soapfactory.createElement("parameternames", "", "");
        //并且为这个标签新增属性 name 以及 value
        names.addAttribute(new QName("soap-enc:arraytype"), "xsd:string["
                + list.size() + "]");
        
        //方法传入的参数list,来自于另外一个方法,其实就是一个保存有value的集合,也就是子标签中需要存入的数据
        //
        SOAPElement nameelement = null;
        for (int i = 0; i < list.size(); i++) {
            //使用soap工厂创建标签
            nameelement = soapfactory.createElement("string", "", "");
            //将集合中的内容保存到创建的string标签中
            nameelement.setTextContent((String) list.get(i));
            //再把存有子标签的数据存到外层标签中
            names.addChildElement(nameelement);
        }
        //在把这个多重子标签,存入到外面的标签中
        informres.addChildElement(names);
        //最后返回这个最外层的part对象,其中就包含了header和body
        return part.getContent();
    }
    
    
    /**
     * 封装请求体中的数据
     * @return
     */
    public List<String> getTestNames() {
        //创建一个List集合,然后调用add方法,存入数据
        List<String> list = new ArrayList<String>();
        list.add("internetgatewaydevice.deviceinfo.x_ct-com_cpu");
        list.add("internetgatewaydevice.deviceinfo.x_ct-com_worktime");
        list.add("internetgatewaydevice.deviceinfo.softwareversion");
        list.add("internetgatewaydevice.landevice.1.wlanconfiguration.1.ssid");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_receivenoise");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_lan-totalbytesreceived");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_lan-totalbytessent");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_wan-totalbytesreceived");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_wan-totalbytessent");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_lan-totalpacketsreceived");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_lan-totalpacketssent");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_wan-totalpacketsreceived");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_wan-totalpacketssent");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.responsepass");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.askpass");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.successpass");
        list.add("internetgatewaydevice.deviceinfo.x_ct-com_temp");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.lan-packetserror");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.lan-totalbytesreceived");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.lan-totalbytessent");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.wan-totalbytesreceived");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.wan-packetserror");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.wan-totalbytessent");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.associateddevice.1.x_ct-com_receiverate");
        list
                .add("internetgatewaydevice.landevice.1.wlanconfiguration.1.associateddevice.1.x_ct-com_sendrate");
        list.add("internetgatewaydevice.deviceinfo.serialnumber");
        list.add("internetgatewaydevice.deviceinfo.manufactureroui");
        return list;
    }

    /**
     * 将soap报文转换成string,在控制台输出
     * @param source
     * @throws Exception
     */
    public void soap2string(Source source) throws Exception {
        //此处的source就是封装的soap请求报文
        if (source != null) {
            //定义一个w3c包中的node对象
            Node root = null;
            //如果请求报文属于DOM类型
            if (source instanceof DOMSource) {
                //就获取node
                root = ((DOMSource) source).getNode();
                //如果请求报文是sax类型
            } else if (source instanceof SAXSource) {
                //最终还是获取其中的元素
                InputSource insource = ((SAXSource) source).getInputSource();
                DocumentBuilderFactory dbf = DocumentBuilderFactory
                        .newInstance();
                dbf.setNamespaceAware(true);
                Document doc = (Document) dbf.newDocumentBuilder().parse(insource);
                root = (Node) doc.getDefaultRootElement();
            }
            //创建transfermerfactory示例,创建transformer对象
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            //设置属性为yes
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            //调用方法,将node类型的请求报文在控制台进行输出
            transformer.transform(new DOMSource(root), new StreamResult(System.out));
        }
    }

    
    /**
     * 封装响应体内容
     * @param part
     * @return
     * @throws Exception
     */
    public Source informresponse(SOAPPart part) throws Exception {
        SOAPEnvelope soapenvelope = part.getEnvelope();
        SOAPBody soapbody = soapenvelope.getBody();
        SOAPElement informres = soapbody.addChildElement("informresponse",
                "cwmp");
        SOAPElement max = SOAPFactory.newInstance().createElement(
                "maxenvelopes", "", "");
        max.setTextContent("1");
        informres.addChildElement(max);
        return part.getContent();
    }

    

    

    
}

 

 

执行结果

 

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cwmp="urn:dslforum-org:cwmp-1-0" xmlns:soap-enc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/xmlschema" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance">
<SOAP-ENV:Header>
<cwmp:id>1</cwmp:id>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<cwmp:getparametervalues>
<parameternames soap-enc:arraytype="xsd:string[27]">
<string>internetgatewaydevice.deviceinfo.x_ct-com_cpu</string>
<string>internetgatewaydevice.deviceinfo.x_ct-com_worktime</string>
<string>internetgatewaydevice.deviceinfo.softwareversion</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.ssid</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_receivenoise</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_lan-totalbytesreceived</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_lan-totalbytessent</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_wan-totalbytesreceived</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_wan-totalbytessent</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_lan-totalpacketsreceived</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_lan-totalpacketssent</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_wan-totalpacketsreceived</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_wan-totalpacketssent</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.responsepass</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.askpass</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.successpass</string>
<string>internetgatewaydevice.deviceinfo.x_ct-com_temp</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.lan-packetserror</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.lan-totalbytesreceived</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.lan-totalbytessent</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.wan-totalbytesreceived</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.wan-packetserror</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.x_ct-com_stat.wan-totalbytessent</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.associateddevice.1.x_ct-com_receiverate</string>
<string>internetgatewaydevice.landevice.1.wlanconfiguration.1.associateddevice.1.x_ct-com_sendrate</string>
<string>internetgatewaydevice.deviceinfo.serialnumber</string>
<string>internetgatewaydevice.deviceinfo.manufactureroui</string>
</parameternames>
</cwmp:getparametervalues>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

 

posted @ 2020-08-01 15:45  Java精进之路  阅读(4962)  评论(0编辑  收藏  举报