几种调用WebService的方法

1. 在JavaScript中调用WebService 

<scriptlanguage="javascript">

functionPostRequestData(URL,data){

varxmlhttp=newActiveXObject("Microsoft.XMLHTTP");

xmlhttp.Open("POST",URL,false);

xmlhttp.SetRequestHeader("Content-Type","text/xml;charset=utf-8");

xmlhttp.SetRequestHeader("SOAPAction","http://tempuri.org/myService/test/isNumner");

try{

xmlhttp.Send(data);

varresult=xmlhttp.status;

}

catch(ex){

return("0"ex.description"|"ex.number);

}

if(result==200){

return("1"xmlhttp.responseText);

}

xmlhttp=null;

}

functionloadit(value){

varurl=’http://localhost/myService/test.asmx’;

vardata;

varr;

data=’<?xmlversion="1.0"encoding="utf-8"?>’;

data=data’<soap:Envelopexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">’;

data=data’<soap:Body>’;

data=data’<isNumnerxmlns="http://tempuri.org/myService/test">’;

data=data’<str>’value’</str>’;

data=data’</isNumner>’;

data=data’</soap:Body>’;

data=data’</soap:Envelope>’;

r=PostRequestData(url,data);

document.write(r);

}

loadit(’5’);

</script>

还可以使用微软的htc组件来实现,可以到这里下载:

http://msdn.microsoft.com/workshop/author/webservice/webservice.htc

<scriptlanguage="javascript">

functiontimer(){

service.useService("http://localhost/myService/test.asmx?WSDL","test");

service.test.callService(callback,"isNumner",’gdh’);

}

functioncallback(res){

if(!res.error)

time.innerText=res.value;

}

</script>

<divid="service"style="behavior:url(webservice.htc)"></div>

<spanid="time"></span>

2.在Asp中

<%@LANGUAGE="VBSCRIPT"CODEPAGE="936"%>

<%

Dimstrxml

Dimstr

’定义soap消息

strxml="<?xmlversion=’1.0’encoding=’tf-8’?>"

strxml=strxml&"<soap:Envelopexmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance’xmlns:xsd=’http://www.w3.org/2001/XMLSchema’xmlns:soap=’http://schemas.xmlsoap.org/soap/envelope/’>"

strxml=strxml&"<soap:Body>"

strxml=strxml&"<isNumnerxmlns=’http://tempuri.org/myService/test’>"

strxml=strxml&"<str>4</str>"

strxml=strxml&"</isNumner>"

strxml=strxml&"</soap:Body>"

strxml=strxml&"</soap:Envelope>"

’定义一个XML的文档对象,将手写的或者接受的XML内容转换成XML对象

’setx=createobject("Microsoft.DOMDocument")

’初始化XML对象

’将手写的SOAP字符串转换为XML对象

’x.loadXMLstrxml

’初始化http对象

Seth=createobject("Microsoft.XMLHTTP")

’向指定的URL发送Post消息

h.open"POST","http://localhost/myService/test.asmx",False

h.setRequestHeader"Content-Type","text/xml"

h.setRequestHeader"SOAPAction","http://tempuri.org/myService/test/isNumner"

h.send(strxml)

Whileh.readyState<>4

Wend

’显示返回的XML信息

str=h.responseText

’将返回的XML信息解析并且显示返回值

’Setx=createobject("MSXML2.DOMDocument")

’x.loadXMLstr

’str=x.childNodes(1).Text

response.write(str)

%>

3.在.net中

在.net中调用WebService就方便多了,没有必要自己写soap消息了,以上都是用XMLHTTP来发送WebService请求的,在.net只要添加了web引用,会自动为你创建一个代理类。然后使用代理类就像用自己定义的类一样方便

相关推荐