簡單對象訪問協議(Simple Object Access Protocol,SOAP)可以使網頁服務器(Web Server)從XML 數據庫中提取數據時,無需花時間去格式化頁面,並能夠讓不同應用程序之間通過HTTP 協議,以 XML 格式互相交換彼此的數據,使這個交換過程與編程語言、平臺和硬件無關。
SOAP 基於 XML 標準,用於在分佈式環境中發送消息,並執行遠程過程調用。使用SOAP,不用考慮任何特定的傳輸協議(儘管通常選用 HTTP 協議),就能使數據序列化。
SOAP 的優點如下:
1.SOAP 是可擴展的。SOAP 無需中斷已有的應用程序,SOAP 客戶端、服務器和協議自身都能發展。而且 SOAP 能極好地支持中間介質和層次化的體系結構。
2.SOAP 是簡單的。客戶端發送一個請求,調用相應的對象,然後服務器返回結果。這些消息是 XML 格式的,並且封裝成符合 HTTP 協議的消息。因此,它符合任何路由器、防火牆或代理服務器的要求。
3.SOAP 是完全和廠商無關的。SOAP 可以相對於平臺、操作系統、目標模型和編程語言獨立實現。另外,傳輸和語言綁定以及數據編碼的參數選擇都是由具體的實現決定的。
4.SOAP 與編程語言無關。SOAP可以使用任何語言來完成,只要客戶端發送正確SOAP 請求(也就是說,傳遞一個合適的參數給一個實際的遠端服務器)。
5.SOAP 沒有對象模型,應用程序可以捆綁在任何對象模型中。
一. SOAP 消息實例
請求時候發送的消息內容如下:<soapenv:Envelope
xmlns:soapenv="http:// schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http:// www.w3.org/2001/XMLSchema"
xmlns:xsi="http:// www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<req:echo xmlns:req="http:// localhost:8080/axis2/services/MySer-vice/">
<req:category>classifieds</req:category>
</req:echo>
</soapenv:Body>
</soapenv:Envelope>
響應時候發送的消息內容如下:
<soapenv:Envelope
xmlns:soapenv="http:// schemas.xmlsoap.org/soap/envelope/"
xmlns:wsa="http:// schemas.xmlsoap.org/ws/2004/08/addressing">
<soapenv:Header>
<wsa:ReplyTo>
<wsa:Address>http:// schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:Address>
</wsa:ReplyTo>
<wsa:From>
<wsa:Address>http:// localhost:8080/axis2/services/MyService</wsa:Address>
</wsa:From>
<wsa:MessageID>ECE5B3F187F29D28BC11433905662036</wsa:MessageID>
</soapenv:Header>
<soapenv:Body>
<req:echo xmlns:req="http:// localhost:8080/axis2/services/MyService/">
<req:category>classifieds</req:category>
</req:echo>
</soapenv:Body>
</soapenv:Envelope>
二. 調用 WebService
步驟1 添加 ksoap2 包。
步驟2 指定 WebService 的命名空間和調用的方法名,如:
SoapObject request =new SoapObject(http:// service,"getName");
第一個參數表示 WebService 的命名空間,可以從 WSDL 文檔中找到;
第二個參數表示要調用的 WebService 方法名。
步驟3 設置調用方法的參數值。設置方法的參數值的代碼如下:
request.addProperty("param1","value");
request.addProperty("param2","value");
只要設置參數的順序一致即可。
步驟4 生成調用 WebService 方法的 SOAP 請求信息。該信息由 SoapSerializationEnvelope對象描述,代碼如下:
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
Envelope.bodyOut = request;
步驟5 創建HttpTransportsSE對象。通過HttpTransportsSE類的構造方法可以指定WebService的WSDL文檔的URL。
HttpTransportSE ht=new HttpTransportSE("http:// fy.webxml.com.cn/webservices/EnglishChinese.asmx?wsdl");
步驟6 使用 call 方法調用 WebService 方法,代碼如下:
ht.call(null,envelope);
步驟7 使用 getResponse 方法獲得 WebService 方法的返回結果,代碼如下
SoapObject soapObject =(SoapObject)envelope.getResponse();
步驟8 解析返回的內容。
補充
中國氣象局的WebService地址
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx