来源:AIR Tip 4: Calling a SOAP Webservice
这些日子,关于如何让单独的应用程序从互联网的不同位置获取数据成了一个普遍的话题。这是可以让AIR成为一个伟大的应用平台的特性中的一个。
在开始之前,我们需要创建一个非常简单的Coldfusion组件。这个组件包含了一个函数”getStuff”。如果你输入了你的名字,它就会返回一个字符串“你的姓名是…”。如果你把它放在你的网站上的某一个地方,就可以通过在文件名后添加”?wsdl”把它发布为一个webservice。这就是你把一个Coldfusion组件转换成一个SOAP协议的Webservice的所有步骤。
参考:Coldfusion 8 and Web Services
注意:我计划写一篇关于如何在JavaScript中使用Consuming Coldfusion Webservices的文章。这篇文章只是提到了这方面的一些基础。
Coldfusion:
-
<cfcomponent>
-
<cffunction name=“getStuff” access=“remote” returnType=“String”>
-
<cfargument name=“personName” required=“true” type=“string” />
-
<cfreturn “Your Name is “ & personName />
-
</cffunction>
-
</cfcomponent>
呼叫一个Webservice,在Flex和Javascript中是完全不同的方法。在Flex中,你只需要简单的使用标签即可。在标签中你可以定义”操作”来和Webservice关联。在这个示例中,我们将定义一个”getStuff”作为其中一个操作。我们将添加一个”onResult”函数到操作的返回事件上。这个处理返回的函数只是简单的将返回结果赋值给场景中的一个文本标签。
mxml:
-
<!–
-
WEB SERVICES
-
–>
-
<mx:WebService
-
id=“sampleService”
-
wsdl=“http://yourDomain/SoapTest.cfc?wsdl”>
-
<mx
peration name=“getStuff” result=“onResult(event)” /> -
</mx:WebService>
Actionscript:
-
import mx.rpc.events.ResultEvent;
-
private function callService(e:MouseEvent):void {
-
sampleService.getStuff.send(myName.text);
-
}
-
private function onResult(e:ResultEvent):void {
-
resultLabel.text = e.result as String;
-
}
在JavaScript中,我们需要使用XMLHTTPRequest对象,就像我们在最后一个Tip所做的。基本上,我们将要添加一对自定义的Header,来传输SOAP数据包。
你可以参考”wsdl”文件来了解SOAP数据包。要参照wsdl文件,你只需在你的浏览器中敲入webservice文件的地址并加上”?wsdl”的后缀即可。wsdl描述了你的Webservice的细节。
参考资料:WSDL Tutorial
-
var xmlhttp;
-
var appXML;
-
function callService() {
-
var myName = document.getElementById(“myName”).value;
-
var url = “http://yourDomain/SoapTest.cfc?wsdl”;
-
xmlhttp = new XMLHttpRequest();
-
xmlhttp.open(“POST”, url, true);
-
xmlhttp.onreadystatechange=function(){
-
if (xmlhttp.readyState==4) {
-
var mainDiv = document.getElementById(‘result’);
-
mainDiv.innerHTML = xmlhttp.responseText;
-
}
-
}
-
xmlhttp.setRequestHeader(“Content-Type”, “text/xml”);
-
xmlhttp.setRequestHeader(‘SOAPAction’,‘http://yourDomain/SoapTest.cfc?wsdl’);
-
xmlhttp.send(“<?xml version=’1.0′ encoding=’UTF-8′?>”+“\n\n“+
-
‘<soapenv:Envelope’+
-
‘ xmlns:soapenv=”http://schemas.xmlsoap.org/soap/envelope/”‘+
-
‘ xmlns:xsd=”http://www.w3.org/2001/XMLSchema”‘+
-
‘ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”>’+
-
‘<soapenv:Body>’+
-
‘<ns1:getStuff xmlns:ns1=”http://communications”‘+
-
‘ soapenv:encodingStyle=”http://schemas.xmlsoap.org/soap/encoding/”>’+
-
‘<personName xsi:type=”xsd:string”>’ + myName + ‘</personName>’+
-
‘</ns1:getStuff>’+
-
‘</soapenv:Body>’+
-
‘</soapenv:Envelope>’);
-
}
对于Flex来说,这是一个非常简单的示例,而在JavaScript中,你必须记住以下的要点:
- 判断各种情况,确保你考虑到了所有的-一个小小的异常就会引发错误
- 你可以将你的函数写在AIR之外,这样你就可以使用类似Firebug的工具来跟踪调试
- 当呼叫一个Coldfunsion Webservice的时候,如果是一个需要RDS密码的页面,一定是你忘记了设置SOAPAction header
- 在xmlhttp.open()函数中使用”POST”标签
Flex Example
Source Code
JavaScript Example
Source Code
Coldfusion Component
Source Code
Tags: AIR, AIR教程