1. 程式人生 > 實用技巧 >soap型別的xml報文如何使用Java生成?

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  xmlns:soap="http://www.w3.org/2001/12/soap-envelope"  soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <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>