[转]几种调用WebService的方法

1.  在JavaScript中调用WebService
 1 None.gif < script language = " javascript " >
 2 None.gif function  PostRequestData(URL,data){
 3 None.gif        var  xmlhttp  =   new  ActiveXObject( " Microsoft.XMLHTTP " );
 4 None.gif       xmlhttp.Open( " POST " ,URL,  false );
 5 None.gif       xmlhttp.SetRequestHeader ( " Content-Type " , " text/xml; charset=utf-8 " );
 6 None.gif       xmlhttp.SetRequestHeader ( " SOAPAction " , " http://tempuri.org/myService/test/isNumner " );
 7 None.gif       
 8 None.gif        try  { 
 9 None.gif              xmlhttp.Send(data); 
10 None.gif               var  result  =  xmlhttp.status;
11 None.gif       }
12 None.gif        catch (ex) {
13 None.gif               return ( " 0 "   +  ex.description  +   " | "   +  ex.number); 
14 None.gif       }
15 None.gif        if (result == 200 ) { 
16 None.gif               return ( " 1 "   +  xmlhttp.responseText); 
17 None.gif       }
18 None.gif       xmlhttp  =   null ;
19 None.gif}
20 None.gif 
21 None.gif function  loadit(value){
22 None.gif        var  url  =  'http: // localhost/myService/test.asmx';
23 None.gif         var  data ;
24 None.gif        var  r;
25 None.gif       
26 None.gif       data  =  ' <? xml version = " 1.0 "  encoding = " utf-8 " ?> ';
27 None.gif       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/ " > ';
28 None.gif    data  =  data  +  ' < soap:Body > ';
29 None.gif    data  =  data  +  ' < isNumner xmlns = " http://tempuri.org/myService/test " > ';
30 None.gif    data  =  data  +  ' < str > ' + value + ' </ str > ';
31 None.gif    data  =  data  +  ' </ isNumner > ';
32 None.gif    data  =  data  +  ' </ soap:Body > ';
33 None.gif    data  =  data  +  ' </ soap:Envelope > ';
34 None.gif       
35 None.gif       r = PostRequestData(url,data);
36 None.gif       document.write(r);                
37 None.gif}
38 None.gifloadit(' 5 ');
39 None.gif </ 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中
 1 None.gif < %@LANGUAGE = " VBSCRIPT "  CODEPAGE = " 936 " % >
 2 None.gif < %
 3 None.gif              Dim  strxml 
 4 None.gif         Dim  str       
 5 None.gif       
 6 None.gif         ' 定义soap消息
 7 None.gif         strxml  =   " <?xml version='1.0' encoding='tf-8'?>"
 8 None.gif         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/'>"
 9 None.gif         strxml  =  strxml  &   " <soap:Body> "
10 None.gif               strxml  =  strxml  &   " <isNumner xmlns='http://tempuri.org/myService/test'>"
11 None.gif         strxml  =  strxml  &   " <str>4</str> "  
12 None.gif        strxml  =  strxml  &   " </isNumner>"
13 None.gif               strxml  =  strxml  &   " </soap:Body> "  
14 None.gif        strxml  =  strxml  &   " </soap:Envelope>"
15 None.gif               
16 None.gif         ' 定义一个XML的文档对象,将手写的或者接受的XML内容转换成XML对象
17 None.gif          ' set x = createobject("Microsoft.DOMDocument")
18 None.gif          ' 初始化XML对象
19 None.gif          ' 将手写的SOAP字符串转换为XML对象
20 None.gif          '  x.loadXML strxml
21 None.gif          ' 初始化http对象
22 None.gif          Set  h  =   createobject " Microsoft.XMLHTTP " )
23 None.gif         ' 向指定的URL发送Post消息
24 None.gif         h.open  " POST " " http://localhost/myService/test.asmx " False
25 None.gif        h.setRequestHeader  " Content-Type " " text/xml"
26 None.gif               h.setRequestHeader  " SOAPAction " " http://tempuri.org/myService/test/isNumner"
27 None.gif         h.send (strxml)
28 None.gif         While  h.readyState  <>   4
29 None.gif         Wend
30 None.gif         ' 显示返回的XML信息
31 None.gif         str  =  h.responseText
32 None.gif         ' 将返回的XML信息解析并且显示返回值
33 None.gif          ' Set x = createobject("MSXML2.DOMDocument")
34 None.gif          '  x.loadXML str
35 None.gif         
36 None.gif         ' str = x.childNodes(1).Text
37 None.gif          
38 None.gif         response.write(str)
39 None.gif 
40 None.gif% >

 3.在.net中
在.net中调用WebService就方便多了,没有必要自己写soap消息了,以上都是用XMLHTTP来发送WebService请求的,在.net只要添加了web引用,会自动为你创建一个代理类。然后使用代理类就像用自己定义的类一样方便。
 
在MSDN里也有:
ms-help://MS.MSDNQTR.2003FEB.2052/behavior/workshop/author/webservice/reference/methods/callservice.htm
以下是userService和callService方法的详细说明:


useService Method


Establishes a friendly name for a Web Service URL, which can then be referenced from script.

Syntax

sElementID.useService(sWebServiceURL, sFriendlyName [, oUseOptions])

Parameters

sElementID Required. The <?XML:NAMESPACE PREFIX = MSHELP /> of the element to which the behavior is attached.
sWebServiceURL Required. String specifying the URL of the Web Service, using one of the following path types. See the examples section, where several variations of this parameter are shown.
Web Service file name A Web service file, which has an .asmx file extension. This short form of the URL is sufficient, provided that the Web service is located in the same folder as the Web page using the WebService behavior. In this case, the ?WSDL query string is assumed by the behavior.
WSDL file name A Web Services Description Language (WSDL) file name. The WSDL file must have a .wsdl file extension.
Full file path Full path to a WebService (.asmx) or WSDL (.wsdl) file. A file path to a Web Service must include the ?WSDL query string. Either a local file path or a URL can be specified.
Relative path A relative path to a WebService (.asmx) or WSDL (.wsdl) file. A file path to a Web Service must include the ?WSDL query string.
sFriendlyName Required. String representing a friendly name for the Web Service URL.
oUseOptions Optional. An instance of the object.

Return Value

No return value.

Remarks

After using this method, the identifier specified in sFriendlyName can be used in script as a reference to the Web Service specified by sWebServiceURL.

The useOptions object can be used when it is necessary to retain the Secure Sockets Layer (SSL) authentication for multiple remote method invocations. For code samples illustrating the use of this technique, see the method.

Examples

The following sample defines the friendly name MyMath from the URL specified in the sWebServiceURL parameter.

<script language="JavaScript">
function init()
{
    service.useService("math.asmx?WSDL","MyMath");
}
</script>
<body οnlοad="init()">
<div id="service" style="behavior:url(webservice.htc)">
</div>
</body>

The following examples illustrate various valid forms of the sWebServiceURL parameter.

The following code snippet illustrates the short form of sWebServiceURL. In this case, the math.asmx file must be located in the same folder as the Web page.

service.useService("math.asmx","MyMath");

The following code snippet illustrates how a WSDL file can be specified for the sWebServiceURL parameter. In this case, the conversion.wsdl file must be located in the same folder as the Web page.

service.useService("conversion.wsdl","MyConverter");

The following code snippet defines the sWebServiceURL parameter as a local file. In this case the ?WSDL query string must be included.

service.useService("C:\inetpub\wwwroot\myproject\myws.asmx?WSDL","MyMath");

The following code snippet defines the sWebServiceURL parameter as the full HTTP file path to the myws.asmx Web service file. In this case the ?WSDL query string must be included.

service.useService("http://localhost/myproject/myws.asmx?WSDL","MyMath");

The following code snippet defines the sWebServiceURL parameter as a relative file path to the myws.asmx Web service file. In this case the ?WSDL query string must be included. This example points to a Web Service file two levels up from the Web page.

service.useService("../../myws.asmx?WSDL","MyMath");

The following code snippet defines the sWebServiceURL parameter as a relative file path to the myws.asmx Web service file. In this case the ?WSDL query string must be included. The path points to the myws.asmx Web Service, which is located in the wsfld subfolder of the Web page.

service.useService("./wsfld/myws.asmx?WSDL","MyMath");



callService Method


Invokes a method that is implemented on a Web Service.

Syntax

iCallID = sElementID.sFriendlyName.callService( [oCallHandler], fo, oParam)

Parameters

sElementID Required. The of the element to which the behavior is attached.
sFriendlyName Required. The friendly name for the Web Service, which is defined by calling the method.
oCallHandler Optional. Name of a script callback function that handles the results returned from this instance of the method call.
fo Required. One of the following possible values.
strFuncName A String representing the name of the remote function being called. The String must be bounded by single or double quotation marks.
objCall A object, which has the necessary properties defined to call a remote function.
oParam Required. One or more comma-delimited parameters, which are passed to the method name specified by fo.

Return Value

In the case of asynchronous communication, returns an Integer, which is a unique identifier for the instance of the method call. In the case of synchronous communication, returns a result object.

Remarks

Using this method causes the WebService behavior to invoke a remote method call on a Web Service.

When the callService method invokes asynchronous communication between the WebService behavior and the Web Service by setting the property to true, the return value of the method is an Integer that identifies the instance of the method call. In this case, an event handler or callback function should be used to process the returned results.

When the callService method invokes synchronous communication between the WebService behavior and the Web Service by setting the async property to false, the return value of the method is a result object.

For an example of using both synchronous and asynchronous communication between the WebService behavior and the Web Service, see the examples on the object page.

If oCallHandler is not specified, then an onresult event handler is used to examine the results of the callService. Using this approach, the properties of the object can be examined to determine if the call was made successfully.

If oCallHandler is specified, then a callback handler function is used to process the results of the method call. The result object is passed to the first parameter of the callback function, so the user specifies the name of the object in the script code. Code samples using each approach are given in .

Regardless of the type of function used to process the results, the properties exposed to script are similar. If an event handler is used, the syntax used to access result information is event.result. If the callback approach is used, the object name is the name of the first parameter in the callback function declaration. For a comprehensive list of property objects returned by a WebService behavior call, see .

When passing an XmlElement  object to a web service using oParam, the Extensible Markup Language (XML) contained in the XmlElement must contain a single root node. The root node is not returned by the object. In the following XML data island, BOOKLIST is the root.

Show Example

<XML ID=myXMLElement>
<?xml version="1.0"?>

<BOOKLIST>
   <BOOK>
      <CODE>16-041</CODE>
      <CATEGORY>HTML</CATEGORY>
      <RELEASE_DATE>1998-03-07</RELEASE_DATE>
      <SALES>127853</SALES>
      <TITLE>Instant HTML</TITLE>
   </BOOK>
   <BOOK>
      <CODE>16-048</CODE>
      <CATEGORY>Scripting</CATEGORY>
      <RELEASE_DATE>1998-04-21</RELEASE_DATE>
      <SALES>375298</SALES>
      <TITLE>Instant JavaScript</TITLE>
   </BOOK>
</BOOKLIST>

</XML>

The following example shows a call to a web service. The element where the WebService Behavior is attached has an id of aaa and the friendly name for the web service is tst.

var x = myXMLElement.documentElement;      
      aaa.tst.callService(myCallBackFunction,"XmlEcho",x);                  

This callback function returns the first child of the booklist element by asking for the zero element child. There is no way to ask for the root or booklist element as it has no parent element.

function myCallBackFunction(res) {
      if (!res.error) {
            var x = res.value;
            var y = x.selectNodes("BOOKLIST")[0].xml;
            alert(y);
      }else{
            alert(res.errorDetail.string);
      }
}

Example

The following example shows how a method named add can be called to calculate the sum of two integers.

<script language="JavaScript">
var iCallID;

function init()
{
    service.useService("/services/math.asmx?WSDL","MyMath");
    iCallID = service.MyMath.callService("add",5,6);
}
</script>
<body οnlοad="init()">
<div id="service" style="behavior:url(webservice.htc)">
</div>
</body>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值