February 02, 2010

Create the custom HTTP Service class and return XML as output in AS3

Hi,
I am creating the custom HTTP service class for accessing URL and get the response from the server and return the result as xml format. Here i attached the code for that.


package service
{
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
import service.MessageService;
import flash.net.URLVariables;
import flash.net.navigateToURL;
import flash.events.IOErrorEvent;
import flash.net.URLRequestMethod;
import flash.events.SecurityErrorEvent;
public class URLService
{
private var _url:String;
private var _callbackObject:Object;
private var _callbackFunction:Function;
private var _urlError:MessageService = new MessageService("URL Error","Warning");
private var _ioError:MessageService = new MessageService("IO Error","Warning");
private var _xmlError:MessageService = new MessageService("XML Error","Warning");
private var _securityError:MessageService = new MessageService("Security Error","Warning");
public function set url(val:String):void
{
if(_url != val)
_url = val;
}
public function set callbackObject(val:Object):void
{
if(_callbackObject != val)
_callbackObject = val;
}
public function set callbackFunction(val:Function):void
{
if(_callbackFunction != val)
_callbackFunction = val;
}
public function URLService()
{
}
public function loadXML(urlVar:URLVariables = null,callbackObject:Object = null,callbackFunction:Function = null):void
{
if(_url && _url != "")
{
var urlLoader:URLLoader = new URLLoader();
var urlRequest:URLRequest = new URLRequest(_url);
if(urlVar)
{
urlRequest.data = urlVar;
urlRequest.method = URLRequestMethod.POST;
}
urlLoader.load(urlRequest);
urlLoader.addEventListener(Event.COMPLETE,onComplete);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR,onIOError);
urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onSecurityError);
_callbackObject = callbackObject;
_callbackFunction = callbackFunction;
}
else
{
_urlError.show();
}
}
public function selfNavigation(urlVar:URLVariables = null):void
{
if(_url && _url != "")
{
var urlRequest:URLRequest = new URLRequest(_url);
if(urlVar)
{
urlRequest.data = urlVar;
urlRequest.method = URLRequestMethod.POST;
}
navigateToURL(urlRequest,"_self");
}
else
{
_urlError.show();
}
}
private function onComplete(evt:Event):void
{
var _xml:XML = XML(evt.target.data);
if(_callbackObject && _callbackFunction != null)
{
_callbackFunction.call(_callbackObject,_xml);
}
else
{
_xmlError.show();
}
}
private function onIOError(evt:IOErrorEvent):void
{
_ioError.show();
}
private function onSecurityError(evt:SecurityErrorEvent):void
{
_securityError.show();
}
}
}

This is very nice class. So use this class and enjoy.

No comments:

Post a Comment