Using web services in Flash/ActionScript has been difficult in the past. Long were the days when one was required to import libraries just to perform simple requests. The good news is those days are long gone and AS3 ushers in an era of ease, just follow this example and you’ll be up in going in no time at all.
For this example I am using a AMFPHP to host my web services and therefore, your calls to your web services may be vary. First, we must create the NetConnection object so that we can use it’s functionality to connect to our services. Compared to previous versions of Flash there isn’t a remoting plugin that is needed, the NetConnection object is natively available within CS4.
//Create the New NetConnection var myService = new NetConnection();
Next, we must target the gateway to be used. When using AMFPHP there are three options: AMF, JSON, and XML. For this tutorial we’ll use the default AMF gateway, but it shouldn’t matter either way.
//Connect to the amfphp gateway myService.connect("http://localhost/api/gateway.php");
Once the correct gateway has been targeted we must create a way to handle the return of the web service. This is done by creating a responder object that will run a certain function whether the request passes or fails.
//Create a new responder object to handle returns var responder = new Responder(onSuccess, onFault);
Finally, we make the actual call to the web service. The first parameter of the call method defines the class and method you would like to call. The second parameter defines which responder to use. Here we use the responder we created in the previous step. Finally, the remaining parameters are all arguments for the method that is being called.
//Call the webservice myService.call("Class.method", responder, arg1, arg2);
Below is the full code. For more information about returning data from AMFPHP or other frameworks check out my other article here.
//Create the New NetConnection var myService = new NetConnection(); //Connect to the amfphp gateway myService.connect("http://localhost/api/gateway.php"); //Create a new responder object to handle returns var responder = new Responder(onSuccess, onFault); //Call the webservice myService.call("Class.method", responder, arg1, arg2);