几种调用WebService的方法
2024-07-21 02:21:22
供稿:网友
1. 在javascript中调用webservice
<script language="javascript">
function postrequestdata(url,data){
var xmlhttp = new activexobject("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);
var result = xmlhttp.status;
}
catch(ex) {
return("0" + ex.description + "|" + ex.number);
}
if(result==200) {
return("1" + xmlhttp.responsetext);
}
xmlhttp = null;
}
function loadit(value){
var url = 'http://localhost/myservice/test.asmx';
var data ;
var r;
data = '<?xml version="1.0" encoding="utf-8"?>';
data = data + '<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/">';
data = data + '<soap:body>';
data = data + '<isnumner xmlns="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
<script language="javascript">
function timer(){
service.useservice("http://localhost/myservice/test.asmx?wsdl","test");
service.test.callservice(callback,"isnumner",'gdh');
}
function callback(res){
if (!res.error)
time.innertext=res.value;
}
</script>
<div id="service" style="behavior:url(webservice.htc)"></div>
<span id="time"></span>
2. 在asp中
<%@language="vbscript" codepage="936"%>
<%
dim strxml
dim str
'定义soap消息
strxml = "<?xml version='1.0' encoding='tf-8'?>"
strxml = strxml & "<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/'>"
strxml = strxml & "<soap:body> "
strxml = strxml & "<isnumner xmlns='http://tempuri.org/myservice/test'>"
strxml = strxml & "<str>4</str>"
strxml = strxml & "</isnumner>"
strxml = strxml & "</soap:body>"
strxml = strxml & "</soap:envelope>"
'定义一个xml的文档对象,将手写的或者接受的xml内容转换成xml对象
'set x = createobject("microsoft.domdocument")
'初始化xml对象
'将手写的soap字符串转换为xml对象
' x.loadxml strxml
'初始化http对象
set h = 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)
while h.readystate <> 4
wend
'显示返回的xml信息
str = h.responsetext
'将返回的xml信息解析并且显示返回值
'set x = createobject("msxml2.domdocument")
' x.loadxml str
'str = x.childnodes(1).text
response.write(str)
%>
3.在.net中
在.net中调用webservice就方便多了,没有必要自己写soap消息了,以上都是用xmlhttp来发送webservice请求的,在.net只要添加了web引用,会自动为你创建一个代理类。然后使用代理类就像用自己定义的类一样方便。