Consuming a Web Service with Flash ActionScript 2.0
August 29th, 2007This is part of my notes while I'm trying to create a Web Service in PHP to be consumed by a SWF application written in ActionScript 2.0.
Consuming a Web Service with ActionScript 2.0
This part is a bit easier. Since the release of Flash MX 2004, the Web Service Classes are available.
First, we create an instance of the WebService class:
-
import mx.services.*;
-
service:WebService = new WebService("http://localhost/my_service_folder/MyService.wsdl");
Right after that we set up the onFault callback function that will be triggered if a error occurs.
-
service.onFault = function(flt:Object){
-
trace("FAULT");
-
trace(flt.faultstring);
-
};
Then we set up the onLoad callback function that will be triggered when the WSDL is loaded.
-
service.onLoad = function(wsdl:Object){
-
trace("onLOAD");
-
testCall();
-
};
In this case, we automatically call the testCall() method when the WSDL is loaded.
-
function testCall(){
-
var pc:PendingCall = service.helloWorld();
The testCall() method calls the helloWorld method on the web service. When you call a method on a WebService object it returns a PendingCall object.
This object will trigger a onResult callback function when the asynchronous response from the server is received. If an error occurs an onFault callback function is triggered.
So we set up 2 callbacks for the PendingCall object:
-
pc.onResult = function(result){
-
trace("onResult");
-
trace(result);
-
};
-
pc.onFault = function(fault:SOAPFault){
-
trace("onFault");
-
trace(fault.faultstring);
-
trace(fault.detail);
-
};
-
}
In the example above if the onResult callback is triggered we just "trace" the result into the output window. If the onFault callback is triggered, we "trace" the faultstring and the detail. These are 2 properties of the SOAPFault object.
A full documentation on the Web Service Classes is available at the LiveDocs.
Below I pasted the entire script without interruptions so you can copy and paste it.
-
import mx.services.*;
-
service:WebService = new WebService("http://localhost/my_service_folder/MyService.wsdl");
-
service.onFault = function(flt:Object){
-
trace("FAULT");
-
trace(flt.faultstring);
-
};
-
service.onLoad = function(wsdl:Object){
-
trace("onLOAD");
-
testCall();
-
};
-
function testCall(){
-
var pc:PendingCall = service.helloWorld();
-
pc.onResult = function(result){
-
trace("onResult");
-
trace(result);
-
};
-
pc.onFault = function(fault:SOAPFault){
-
trace("onFault");
-
trace(fault.faultstring);
-
trace(fault.detail);
-
};
-
}
June 20th, 2009 at 12:38
This code doesn't work. When I copy and paste it I get a syntax error on line 2.
July 24th, 2009 at 13:51
Hi, very very helpful! Simple, to the point description of how to consumer webservice in actionscript.
Thanks a ton!!
November 18th, 2009 at 02:54
Simple and clean. Well done!