Using Web Services

Difficulty: Beginner
Using Web Services

Problem

You want to regularly update dynamic data from distant Web services.

Solution

Use an object that implements the WebService interface and run the send() method at a specified interval by using the flash.utils.setInterval() function.

Discussion

The WebService interface defines a very easy-to-use API to work with Web services, such as RSS feeds or REST APIs. The WebServiceBase class provides a basic set of properties and methods to simply call these services and treat the results.

By extending the WebServiceBase class, you can create a custom object that will be able to deal with a specific Web service.

First of all, lets create a PHP file, called "gateway.php", to emulate a Web service:

<?php echo "Hello World!"; ?>

Now, we import the WebServiceBase class to create a new WebService object. The WebServiceBase constructor function accepts one parameter which is the URL of the distant service:

import org.flashapi.swing.net.rpc.WebServiceBase;

var service:WebServiceBase = new WebServiceBase("gateway.php");

To get the result, we must add an event listener to the WebService instance. The WebServiceEvent defines several events, including "result" which is fired each time an answer is returned from the distant service.

import org.flashapi.swing.event.WebServiceEvent;
service.addEventListener(WebServiceEvent.RESULT, resultHandler);

The above resultHandler function outputs the message returned from the PHP-emulated service:

function resultHandler(e:WebServiceEvent):void {
	trace(e.result.toString());
}

Now we have defined all the pieces of code we need to interact with the distant service, we just call it by using the send() method.

If you want to have regular updates of the data returned by a Web service, you can simply run the send() method from the setInterval() function:

import org.flashapi.swing.net.rpc.WebServiceBase;
import org.flashapi.swing.event.WebServiceEvent;

var service:WebServiceBase = new WebServiceBase("gateway.php");
service.addEventListener(WebServiceEvent.RESULT, resultHandler);

function resultHandler(e:WebServiceEvent):void {
	trace(e.result.toString());
}

setInterval(service.send, 1000);

Share this article:

Comments:

There are no comments yet for this article.

Leave a reply

Your email is required but will not be displayed.

To prevent abusive emails, please enter the numbers you see in the image below:

Security code