HTML中调用带有SoapHeader头的WebService的两种方法

时间:2023-03-09 02:59:10
HTML中调用带有SoapHeader头的WebService的两种方法

第一种:

function CallWebMethodWithHeader() {
var soapXML =
"<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
" <soap:Header>" +
"<TestHeader xmlns='http://tempuri.org/'>" +
"<HeaderData xmlns='http://tempuri.org/'>111111111111</HeaderData>" +
"</TestHeader>" +
"</soap:Header>" +
"<soap:Body>" +
"<TestSoapHeader xmlns='http://tempuri.org/' />" +
"</soap:Body>" +
"</soap:Envelope>"; $.ajax({
url: "http://localhost:40800/WebService/SoadHeader.asmx?op=TestSoapHeader",
type: "POST",
dataType: "xml",
contentType: "text/xml; charset=utf-8",
data: soapXML,
beforeSend: function (xhr) {
xhr.setRequestHeader('SOAPAction', 'http://tempuri.org/TestSoapHeader'); }, success: function (data) {
console.log(data);
},
error: function (err) {
alert("webmethod call failed");
} }); } //调用
CallWebMethodWithHeader();

第二种:采用Jquery Soap插件

插件地址:https://github.com/doedje/jquery.soap

这个插件在添加SOAPHeader的时候有两个问题:1、生成提交的XML中缺少命名空间;2、DEMO中提示可以直接toJSON,实际测试有问题。

关于第一个问题,需要在插件源代码的soapHeader配置部分增加一行代码,相关代码如下:

// SOAPHeader
//soapObject.attr('xmlns', config.namespaceURL);
if (!!config.SOAPHeader) {
var soapHeader = SOAPTool.processData({
data: config.SOAPHeader,
name: 'temp',
prefix: ''
}); if (!!soapHeader) {
if (soapHeader.hasChildren()) {
for (var j in soapHeader.children) {
soapEnvelope.addHeader(soapHeader.children[j]);
//需要增加下面这行代码
soapHeader.children[j].attr('xmlns', config.namespaceURL);
}
} else {
soapEnvelope.addHeader(soapHeader);
}
}
}

客户端调用:

$.soap({
url: 'http://localhost:40800/WebService/SoadHeader.asmx?op=',
method: 'TestSoapHeader',
namespaceURL: 'http://tempuri.org/',
SOAPHeader: {
TestHeader:{ HeaderData: 'Basic'}
},
data:{
},
success: function (soapResponse) {
var x2js = new X2JS();
var jsonObj = x2js.xml_str2json(soapResponse);
console.log(jsonObj.Envelope.Body.TestSoapHeaderResponse);
// do stuff with soapResponse
// if you want to have the response as JSON use soapResponse.toJSON();
// or soapResponse.toString() to get XML string
// or soapResponse.toXML() to get XML DOM
},
error: function (SOAPResponse) {
//console.log(SOAPResponse);
}
});