翻閱網路上大量的 jQuery 呼叫 WebService 範例後,會發現一個耐人尋味的現象:幾乎所有教學都在傳 JSON。問題在於,WebService 的本質是走 SOAP 協議的,而 .NET 的 WebService 額外「順便」支援了 JSON,Java 那一套標準 SOAP 服務(例如 Xfire 發布的端點)並不吃這一套。這也難怪很多人照著貼上程式碼,換到 Java 端就完全跑不動。
於是我把 WSDL 文件從頭讀了一遍,自己動手做了一個可運行的範例。關鍵點只有兩個:contentType 必須是 text/xml,data 必須是一段符合 SOAP 1.1 规范的 XML 字串,而不是 JSON。
$(function () {
$("#btnWs").click(btnAjaxPost);
});
function btnAjaxPost(event) {
$.ajax({
type: "POST",
contentType: "text/xml",
url: "https://*****/WebServiceTest/services/HelloWorldService",
data: getPostData(), // 這裡不能給 JSON,要給 SOAP 封包
dataType: 'xml', // 設成 xml 或不設;設成 json 會讓回傳值變成 null
success: function (xml) {
// 瀏覽器差異大,IE 與非 IE 的解析方式完全不同
if ($.browser.msie) {
$("#result").append(
xml.getElementsByTagName("ns1:out")[0].childNodes[0].nodeValue + "<br/>");
} else {
$(xml).find("out").each(function () {
$("#result").append($(this).text() + "<br/>");
});
}
},
error: function (x, e) {
alert('error:' + x.responseText);
},
complete: function (x) {
// alert('complete:' + x.responseText);
}
});
}
從 WSDL 可以讀出兩件事:方法名稱是 sayHelloWorld,傳入參數名稱是 parameters。命名空間則要對上服務端宣告的 https://tempuri.org/。
function getPostData() {
// 依 WSDL 定義組出符合 SOAP 協議的請求本文
var postdata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
postdata += "<soap:Envelope xmlns:xsi=\"https://www.w3.org/2001/XMLSchema-instance\" "
+ "xmlns:xsd=\"https://www.w3.org/2001/XMLSchema\" "
+ "xmlns:soap=\"https://schemas.xmlsoap.org/soap/envelope/\">";
postdata += "<soap:Body><sayHelloWorld xmlns=\"https://tempuri.org/\">";
postdata += "<parameters>" + $("#txtName").val() + "</parameters>";
postdata += "</sayHelloWorld></soap:Body>";
postdata += "</soap:Envelope>";
return postdata;
}
第一,跨網域呼叫會被同源政策攔下,本機測試時最好把服務與頁面放在同一個站台下,或改用 JSONP/代理端點。第二,回傳節點名稱會帶命名空間前綴(如 ns1:out),IE 用 getElementsByTagName 取,非 IE 用 find("out"),兩條路徑都要寫。第三,若服務端回的是 SOAP Fault,error 回呼裡的 responseText 會是唯一線索,記得先把它印出來看。
完整專案原始碼(Java WebService 範例):
https://theyounglearningmaterials.googlecode.com/svn/trunk/JavaWebServices/WebServiceTest/
後續所有學習範例都會集中在
https://theyounglearningmaterials.googlecode.com/svn/trunk/
底下,方便管理、也避免檔案散失。