Flex Introduction - 5

Last time, I mentioned there are three ways talking to server-side, HTTPService, WebService, and RemoteObject. Today, I will introduce the HTTPService.
Basically, using HTTPService is easy. Here is the example:


private function useHttpService():void {
var params:Object = {firstName:fNameSearch.text, lastName:lNameSearch.text};
var service:HTTPService = new HTTPService();
service.url = "http://localhost:9080/example/userProfile.action";
service.method = "POST";
service.resultFormat = "text";
service.useProxy = false;
service.showBusyCursor = true;
service.addEventListener(ResultEvent.RESULT, resultHandler);
service.addEventListener(FaultEvent.FAULT, faultHandler);
service.send(params);
}
private function resultHandler(event:ResultEvent):void {
var json:Object = JSON.decode(event.result as String);
var ary:Array = json.profileList as Array;
result = new ArrayCollection(ary);
dg.dataProvider = result;
}
private function faultHandler(event:FaultEvent):void {
Alert.show("Error: " + event.fault.faultString, "Application Error");
}

To trigger this HTTPService call, you can call the function "useHttpService()" in a click event. And a request will be sent to service side "http://localhost:9080/example/userProfile.action". This will call the "userProfile" action servlet (Note: This is for Struts2.) Also, I tell Flex to use POST method and the result format is "text".
There are two listeners I've added into the function. The first one is to tell what happens if server returns 200 (successful) and what happens if server has error (it could be error codes 500s, 400s or 300s, etc.)
Let's assume everything is okay. So, the result will be returned in resultHandler() function as JSON format. After that, I just convert the JSON object to ArrayCollection and then bind it into DataGrid 'dg'.

So, why JSON format? Basically, you can return as XML, JSON, String, etc. However, JSON is faster than XML parser and that's why I choose JSON. Next time, we will see the code from Server side and see how the servlet returns JSON by using combination of Struts2 + JSON Plugin.