mike chambers | about

Calling Web Services from Flash MX

There has been a lot of discussion within the Flash Community concerning calling web services from Macromedia Flash. This seems to have been prompted by google making available a web service for their search engine.
So i thought i would give a quick sneak peek of calling web services from Flash using Flash Remoting. The example linked below calls the google web service to do a search (i’ll let the code speak for itself).

The example is commented. Post any questions / comments in the comments section.

Code here:

#include "NetServices.as"
#include "NetDebug.as"

//settings for google query
var params = new Object();
params.key = "XXXXXXXXXXXXXXXXXXXXXXXXXXX"; //enter your own google key here
params.q = "Macromedia MX"; //this is the search term

//the rest are required, but you can leave them at their defaults
params.start = 0;
params.maxResults = 10;
params.filter = true;
params.restrict = "";
params.safesearch = true;
params.lr = "lang_en";
params.ie = "latin1";
params.oe = "latin1";


/*  This object will be used to catch any responses from server / web service */
Result = function()
{
	/* 
		onResult is called when data is loaded
	
		data is a GoogleSearchResult object.
	*/
	this.onResult = function(data)
	{
		trace("Estimated Total Results : " + data.estimatedTotalResultsCount);
		trace("Search Time			   : " + data.searchTime);
		
		/* resultElements is ResultElementArray object containing ResultElement objects */
		trace("Results          	   : " + data.resultElements);

		/*
			We can either pass the ResultElementArray to a component
		*/
		lBox.setDataProvider(data.resultElements);
		
		/*
			Or print out the search results one by one.

			Here we just print the first result to the output window.
		*/
		trace("----------First Result Data --------");
		
		var fResult = data.resultElements[0];
		for(var x in fResult)
		{
			trace(x + " : " + fResult[x]);
		}
	}
	
	/* onStatus is called if an error occurs */
	this.onStatus = function(error)
	{
		trace("Error : " + error.description);
	}
}

NetServices.setDefaultGatewayUrl("http://localhost:8500/flashservices/gateway/");
var gw = NetServices.createGatewayConnection();
var google = gw.GetService("http://localhost:8500/google/GoogleSearch.wsdl",new Result());

/* This is where the google web service is actually called */
google.doGoogleSearch(params);
Tags:
twitter github flickr behance