现在的位置: 首页 > 综合 > 正文

[转]几种调用WebService的方法

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

 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 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 onload="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 World Wide Web link 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

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;      // get the xmlelement object
      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 onload="init()">
<div id="service" style="behavior:url(webservice.htc)">
</div>
</body>

抱歉!评论已关闭.