highest safe dose of levitralevitra takecompare levitra cialis viagrageneric levitra onlinecheap herbal vardenafillevitra online uklevitra increases sperm countwomen\s vardenafillevitra samplelevitra slide kitmail order levitralevitra prescription onlinesoft levitraPurchase Levitra pillthe buy levitrageneric levitra canadaproduct team levitravardenafil 90 pills Buylevitra sale 32free sample prescription for levitralevitra trial offermedication levitranon prescription vardenafillevitra online shop in uklevitra medicareinformation levitralevitra on line saleslevitra japanqry vardenafilSale vardenafil 20 pillscheap herbal levitraidentify vardenafillevitra alternative lavitraflomax levitraGeneric Levitra 20 mg Salelevitra couponus vardenafilbuy levitra 10mglevitra commercial modelsforum levitraOnline vardenafil Courier shipping10 mg vs 20 mg levitralevitra dosage directionstoo much levitrawhere to puchase vardenafil onlinecheap levitra on linecialis levitra vardenafilhow levitra workqueen levitravardenafil 180 pills orderlevitra beogradlevitra birth control pillslevitra orallow cost alternatives and vardenafilLevitra 120 pills BuyBuy vardenafil Free Airmail shippingordering levitra onlinecialis levitra viagra comparebuy vardenafil online australiaorder levitra cheap pricevardenafil saleanyone tried generic levitravardenafil softabsbuy levitra viagra onlinelevitra user reviewneed for increasing amounts of levitralevitra online purchasewhat is vardenafilvardenafil rrp australia costvardenafil fast shippingvardenafil no prescriptionlevitra online gamblingviva levitrawomen taking levitradiscount vardenafil onlinelevitra sampleslowest price levitra generic onlinelevitra penslevitra and flomaxpurchase levitra 60 pillslevitra side effectorder Levitra 10 mgalternative to levitraby levitra priceBuy vardenafil Courier shippinguk alternative vardenafillevitra sarasota floridaprice on levitralevitra or viagra which is betterlevitra from canadalevitra ad reviewtry levitra for freeacheter du levitrawholesale vardenafillevitra where to buycomparison levitra cialistoo much vardenafilcomparison of levitra and viagradosage for levitrageneric mexican levitrahow to buy levitragenuine vardenafilcialis levitra viagra which is bettervardenafil onlinerelative costs of cialis levitraget vardenafil drug onlinelevitra vs viagra vs cialisorder levitra 30 pillssample of vardenafildiscount cialis levitra online canadanatural equivelant ingredient in levitraorder levitravardenafil 20 pills onlinecialis vardenafilreviews of viagra cialis and levitraeuropean vardenafilcanada in levitraPurchase Generic vardenafil 20 mglevitra 100mglevitra propafenoneinfo levitrauk levitra saleswoman\s levitraOnline Levitra 120 pillspurchase vardenafil 10 mggeneric levitra tab 20mgvardenafil australiacompare viagra to levitravardenafil 6 free samplesvardenafil canadian drugslevitra generikaOnline Levitra 20 mgwhat does vardenafil dovardenafil uterine thicknesslevitra hourslevitra cost of salesGeneric Levitra 10 mg ordervardenafil lengthvardenafil sideviagra cyalis levitra comparedlevitra pictureslevitra for salevardenafil online cheapLevitra 20 pills BuyLevitra Free Airmail shipping onlinebuy levitra online atgeneric levitra manufacturermaximum dosage levitravardenafil Courier shipping SaleSale vardenafil 10 pillswhat is better levitra or viagradifference between cialis levitra viagralevitracialis compare levitramedical drug levitravardenafil patent levitraprice levitralevitra tablevardenafil vs cialisvardenafil 180 pills Buyeffects of levitraget levitra drug onlinedreampharmaceuticals from levitranew erectile drug vardenafilover the counter levitrabuy levitra australiangeneric vardenafil indiacialis dysfunction erectile levitralevitra side effects visiondiscount levitra pillsOnline vardenafil Free Insurancecanadian pharmacy levitralevitra low costlevitra reviewsPurchase Generic Levitranew erectile drug levitravardenafil usevardenafil pricinglevitra herb alternativeOrder Generic vardenafil 20 mgvardenafil max complaintsfree vardenafil sampleslevitra or viagraSale Levitra 10 mglevitra lowest pricecheap vardenafil siproblems with levitralevitra suppliers in the ukwatermelon levitralevitra to buy new zealandmedicine levitralevitra 10 mg tabletbuy levitra online dream pharmaceuticalsoft levitra mastercardlevitra ingredientsvardenafil perscription onlinegeneric levitra cheapcanadian vardenafillevitra and price listvardenafil hcl 20 mgbayer levitra onlinefree trial of vardenafilbuy levitra delived fed exrecreational levitra usekey buy levitra onlinelevitrabuy cheap levitra onlineGeneric vardenafil 10 mg onlineorder cheap levitra faslevitra by bayervardenafil 30 pills onlineship free vardenafil sampleregalis vardenafilbuy levitra usvardenafil super activeLevitra 180 pills Buydrug levitra newvardenafil purchasevardenafil 30 pills orderprofessional levitra627 discount levitra online 903levitra and premature ejaculationpfizer vardenafilcialis levitra or viagralevitra twice a daysnorting levitraorder 50mg levitrabuy Levitra 10mgLevitra pills Buybuy cheap levitra onlinelevitra vs cialis reviewbrand name levitratake levitralevitra pill pricevardenafil optionslevitra cialis for womenhow to get levitravardenafil alternativespharmacy vardenafilbuy levitra ukvardenafil hcl 20mg tab side effectsbuy levitra in ukgeneric levitra professionallevitra efectosgeneric levitra effectiveorder vardenafil 10 mg2buy levitra online viagralevitra worksflomax and levitraSale Levitra Airmail shippingclinical data levitrageneric levitra soft tab fasti have levitrarx levitravardenafil 120 pillsbuy vardenafil meds onlinevardenafil online no prescriptionis vardenafil professional realcheap vardenafil walmartuk levitrabuy levitra in canadavardenafil from indiafree sample pack of levitramature vardenafilhow long is levitra effectivelevitra price comparisonlevitra storyvardenafil effekter biverkningarvardenafil for teenscheapest levitra in ukfda on levitralevitra fedexgeneric vardenafil mexicosample levitralevitra best resultslevitra substitutelevitra generic soft tabsafe maximum levitra dosagelevitra online cheapLevitra pills onlinevardenafil free sampleslevitra dysfunction erectilelevitra rxlevitra from mexicovardenafil drug prescriptionvardenafil discountsOrder vardenafil Free Insurancelevitra precautionsbuy buy cheap cheap levitra levitralevitra v s levitravardenafil sex dominationlevitra success storieslevitra for womanvardenafil 20 mg paypallevitra sverigecheap levitra overnightOrder Levitra Airmail shippingbuy vardenafil 10 pillscounterfeit levitrabuy levitra 30 pillsvardenafil suppliers in the ukvardenafil effective timeLevitra Courier shipping orderorder levitra from canadabuy drug satellite tv levitralevitra 20order vardenafillevitra wholesale onlinelevitra fast overnight delivery usa onlyuser review levitracialis and levitra generic brandgeneric levitralevitracialis generic levitra viagralevitra online usdoes levitra look likebuy levitra lowest pricescompare viagra levitralevitra on linesample of levitraviagra cialis levitra candian pharmacy safecheap vardenafil nzprice of vardenafilbuy online vardenafilnatural levitrageneric levitra pillsnatural equivalent ingredient in vardenafilordering vardenafillevitra free pillsbuy vardenafil in uklevitra order2buy generic levitralevitra pay with paypalvardenafil in uk onlineglaxo levitravardenafil and commercialvardenafil 50 mglevitra with lisinoprilwhat does levitra dobuy levitra medicationlevitra couchcan a woman take levitravardenafil 10mgreal levitralevitra offervardenafil 10 pills Buylowest prices for levitracanada vardenafilfree levitra pillscheapest online cost for levitravardenafil generic pricevardenafil gelvardenafil mexicovardenafil ukon levitralevitra discussiongeneric name of levitrabuy vardenafil 30 pillslevitra price walmartlevitra time effectiveLevitra Free Airmail shipping Salevardenafil wholesale onlinelevitra andacheter levitra francecheap vardenafil 20 mgwoman in levitra commercialpill identification levitrageneric discount levitralevitra 20 mg dosagelevitra interactionsoriginal levitrapurchase vardenafil 10mgbuy levitra online in 24 hoursvardenafil for sale without a prescriptionlevitrabuy levitra onlineLevitra 10 mg onlineviagra medication prescription levitra cialis propecialevitra anwendungviagra cialis levitra vpxlcan woman take levitrabuy levitra upsLevitra 90 pills BuySale vardenafil pillovernight vardenafilvardenafil reviewslevitra drugswatermellon vardenafilbuy levitra without prescriptionquery lowest levitra price onlinebuying levitra onlinelevitra generic priceusing levitralevitra for freegeneric viagra levitra generic cialis pillsvardenafil testimonialGeneric Levitra 20 mg ordervardenafil on linevardenafil Free Airmail shipping onlinehow long will levitra lastq buy levitraorder discount levitraviagra levitra cialis offerslevitra and bayercheap pharmacy viagra cialis levitralevitra vs viagra reviewswomans levitraburing levitra onlinelevitra softbuy cheap levitralevitra drug prescriptionbuy levitra in englandvardenafil Salevardenafil for daily useactress in levitra commercialbuy levitra with pay palcheap vardenafil overnightindia vardenafilvardenafil pill orderbuy levitra online 35008 buylevitra pill cuttervardenafil sizevardenafil uk cost pillvardenafil 60 pills onlinegeneric soft tabs vardenafilkey buy levitra cheaplevitra cheap buy onlinelow price vardenafilcheap vardenafil tabletslevitra onlinevardenafil 20 mg orderblindness cialis levitravardenafil levitra onlinelevitra faqsplitting levitravardenafil in ukvardenafil lowest priceprozac interactions with viagra cialis levitrakeywords cialis levitra sales viagrahow quick does levitra workwhat is levitra productPurchase vardenafil Free Airmail shippingLevitra 20 mgcomparison of cialis levitra and viagraovernight shipping of professional vardenafilbenefits of levitralevitra vs viagra which is better2buy cheap levitra onlinelevitra prices american pharmaciesvardenafil online overnightdiscount levitra cialis viagrabuy cheap levitra xanax xenicalorder levitra onlinecheapest vardenafil substitute vardenafilbuy vardenafil cialasbuy cheap generic levitra pharmacy onlinelevitra soft tablevitra third quarter 2004 saleslevitra bestellenvardenafil fedexviva levitra commercialLevitra Courier shipping Salecheapest vardenafil professionalLevitra 10 pills Buycheap vardenafil canadaOnline Levitra Free Airmail shippingfull information levitradiscounted vardenafillevitra substitutesLevitra 20 mg Buylevitra 20 mg bayerbuy vardenafil delived fed exforeign cialis levitra pillswomen vardenafilvardenafil overnight shippingcan women use levitravardenafil Buyvardenafil propafenonelevitra provardenafil impotence drug eli lilly cobuy levitra viagralevitra web siteship free levitra sampleorder levitra without prescriptionfree levitra onlinesuper levitralevitra in ukcompare viagra 26 levitra2cheap levitra onlineOrder vardenafilvardenafil Courier shipping orderbuy vardenafilvardenafil storieslevitra successdiscount levitra purchasecheapest levitra substitute sildenafillevitra cialis viagra comparebuy vardenafil online in ukLevitra 20 mg onlineordering levitraconnecticut levitra vardenafillevitra productsLevitra Free Airmail shipping BuyGeneric vardenafil 10 mg Sale
intense creativity » Tutorial - Consuming REST web services in ActionScript 3 - Part 4

Tutorial - Consuming REST web services in ActionScript 3 - Part 4

Hi Everyone,

this is a follow-up to the following posts:

In this post, I will add code to identify each request uniquely, give you a class called "AbstractClient" that will handle most of the mechanics and is easily extended. The idea is to give you a base on which to build. Essentially, for every service call you will want to make you will need 2 functions:

  • A public function that will send the request out
  • a protected function that will receive the response, digest it and dispatch an event

For those who'd like to go ahead and enjoy the goods right away, I will write this tutorial so it can be read and understood on it's own.

Class Member Variables
AbstractClient will contain 2 variables:

  • protected var _requestQueue:Array; -- used to store current requests
  • protected var _requestSequence:Number = 0; -- used to give each request a unique identifier

So here is what it looks like so far:

Actionscript:
  1. package maax.ws
  2. {
  3.     import flash.events.EventDispatcher;   
  4.    
  5.     public class AbstractClient extends EventDispatcher
  6.     {
  7.         protected var _requestQueue:Array;
  8.         protected var _requestSequence:Number = 0;   
  9.        
  10.         public function AbstractClient()
  11.         {
  12.             _requestQueue = [];
  13.             _requestSequence = 0;
  14.         }
  15.     }
  16. }

So the queue is initialized to an empty array, and the sequence is set to 0.

The core functionality
So the idea is to keep currently occuring requests in the queue, and to describe the request using a wrapper object. This object will contain:

  • requestId
  • loader (URLLoader reference) that is running it
  • success flag
  • any other information the caller wishes to have

The wrapper object is passed as a parameter to the public function being called from the outside. We then add information into it and put it in the _requestQueue.

When the loader (URLLoader) receives the result, we get the proper wrapper object from the queue, and then use this information as necessary.

Here is the main function, called runLoader.

Actionscript:
  1. protected function runLoader(request:URLRequest, doComplete:Function, wrapper:Object):Number
  2. {      
  3.     var loader:URLLoader = new URLLoader();
  4.     loader.dataFormat = URLLoaderDataFormat.TEXT;         
  5.     loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, doHttpStatus);
  6.     loader.addEventListener(IOErrorEvent.IO_ERROR, doIOError);
  7.     loader.addEventListener(ProgressEvent.PROGRESS, handleProgress);
  8.     loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR , doSecurityError);
  9.     loader.addEventListener(Event.COMPLETE, doComplete);
  10.                
  11.     loader.load(request);
  12.            
  13.     wrapper.id = _requestSequence++;
  14.     wrapper.success = false;
  15.     wrapper.loader = loader;
  16.     _requestQueue.push(wrapper);
  17.            
  18.     return wrapper.id;
  19. }

So basically the loader is created, we set the right format for the data to be sent and received, listen to all potential events. The Event.COMPLETE event handler is specified by the subclass calling this function. Then assign the wrapper properties and push it in the queue, and return the id of this request to the subclass' function.

Error Handling
What's left is the code to handle errors. This is, however, not fully implemented yet. First lets get a few function to retrieve the right Wrapper objects from the queue..

Actionscript:
  1. protected function getLoaderIndex(loader:URLLoader):Number
  2. {
  3.     for (var i:Number = 0; i <_requestQueue.length; i++)
  4.     {
  5.         if (_requestQueue[i].loader == loader)
  6.             return i;
  7.     }
  8.            
  9.     return -1;
  10. }
  11.        
  12. protected function getWrapper(loader:URLLoader):Object
  13. {
  14.     return _requestQueue[getLoaderIndex(loader)];
  15. }

Next the actual error handling functions, which you will have to implement yourself..

Actionscript:
  1. protected function doHttpStatus(evt:HTTPStatusEvent):void
  2. {
  3.     //trace("WSClient.doHttpStatus:" + evt.status);
  4. }
  5.        
  6. protected function doIOError(evt:IOErrorEvent):void
  7. {
  8.     var wrapper:Object = getWrapper(evt.target as URLLoader);
  9.     if(!wrapper.success)
  10.         trace("WSClient.doIOError(" + evt.toString());
  11.     else
  12.         trace("success!");
  13. }
  14.        
  15. protected function doSecurityError(evt:SecurityErrorEvent):void
  16. {
  17.     trace("WSClient.doSecurityError("+evt.toString());   
  18. }
  19.  
  20. protected function handleIOError(evt:IOErrorEvent):void
  21. {
  22.     trace("ioError on loader:" + getLoaderIndex(evt.target as URLLoader));
  23. }

Handling Progress
You could handle progress from a request, although I doubt that in most cases the "bytesTotal" will be know. Here is some sample code:

Actionscript:
  1. protected function handleProgress(evt:ProgressEvent):void
  2. {
  3.     var percent:Number = Math.round(evt.bytesLoaded / evt.bytesTotal * 100);
  4.     var wrapper:Object = getWrapper(evt.target as URLLoader);
  5.     wrapper.loaded = percent;
  6. }

AbstractClient Complete Source
here is the source, complete..

Actionscript:
  1. package newcommerce.ws
  2. {
  3.     import flash.events.EventDispatcher;
  4.     import flash.net.URLRequest;
  5.     import flash.net.URLLoader;
  6.     import flash.net.URLLoaderDataFormat;
  7.     import flash.events.HTTPStatusEvent;
  8.     import flash.events.IOErrorEvent;
  9.     import flash.events.ProgressEvent;
  10.     import flash.events.SecurityErrorEvent;
  11.     import flash.events.Event;
  12.     import maax.reference.Params;
  13.    
  14.     /**
  15.      * ...
  16.      * @author Martin Legris ( http://blog.martinlegris.com )
  17.      */
  18.     public class AbstractClient extends EventDispatcher
  19.     {
  20.         protected var _requestQueue:Array;
  21.         protected var _requestSequence:Number = 0;
  22.        
  23.         public function AbstractClient()
  24.         {
  25.             _requestQueue = [];
  26.             _requestSequence = 0;
  27.         }
  28.        
  29.         protected function runLoader(request:URLRequest, doComplete:Function, wrapper:Object):Number
  30.         {         
  31.             var loader:URLLoader = new URLLoader();
  32.             loader.dataFormat = URLLoaderDataFormat.TEXT;         
  33.             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, doHttpStatus);
  34.             loader.addEventListener(IOErrorEvent.IO_ERROR, doIOError);
  35.             loader.addEventListener(ProgressEvent.PROGRESS, handleProgress);
  36.             loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR , doSecurityError);
  37.             loader.addEventListener(Event.COMPLETE, doComplete);
  38.             loader.load(request);
  39.            
  40.             wrapper.id = _requestSequence++;
  41.             wrapper.success = false;
  42.             wrapper.loader = loader;
  43.             _requestQueue.push(wrapper);
  44.            
  45.             return _requestSequence - 1;
  46.         }
  47.        
  48.         protected function getLoaderIndex(loader:URLLoader):Number
  49.         {
  50.             for (var i:Number = 0; i <_requestQueue.length; i++)
  51.             {
  52.                 if (_requestQueue[i].loader == loader)
  53.                     return i;
  54.             }
  55.            
  56.             return -1;
  57.         }
  58.        
  59.         protected function getWrapper(loader:URLLoader):Object
  60.         {
  61.             return _requestQueue[getLoaderIndex(loader)];
  62.         }
  63.        
  64.         protected function doHttpStatus(evt:HTTPStatusEvent):void
  65.         {
  66.             //trace("WSClient.doHttpStatus:" + evt.status);
  67.         }
  68.        
  69.         protected function doIOError(evt:IOErrorEvent):void
  70.         {
  71.             var wrapper:Object = getWrapper(evt.target as URLLoader);
  72.             if(!wrapper.success)
  73.                 trace("WSClient.doIOError(" + evt.toString());
  74.             else
  75.                 trace("success!");
  76.         }
  77.        
  78.         protected function doSecurityError(evt:SecurityErrorEvent):void
  79.         {
  80.             trace("WSClient.doSecurityError("+evt.toString());   
  81.         }
  82.  
  83.         protected function handleProgress(evt:ProgressEvent):void
  84.         {
  85.             var percent:Number = Math.round(evt.bytesLoaded / evt.bytesTotal * 100);
  86.             var wrapper:Object = getWrapper(evt.target as URLLoader);
  87.             wrapper.loaded = percent;
  88.         }
  89.        
  90.         protected function handleIOError(evt:IOErrorEvent):void
  91.         {
  92.             trace("ioError on loader:" + getLoaderIndex(evt.target as URLLoader));
  93.         }
  94.     }
  95. }

Sample Usage
So as per Part 2, we woud like it to be a singleton. So here is the start..

Actionscript:
  1. package newcommerce.ws
  2. {
  3.     /**
  4.      * ...
  5.      * @author Martin Legris ( http://blog.martinlegris.com )
  6.      */
  7.     public class WSClient extends AbstractClient
  8.     {
  9.         protected static var _instance:WSClient;
  10.         public static function getInstance():WSClient
  11.         {
  12.             if (_instance == null)
  13.                 _instance = new WSClient();
  14.                
  15.             return _instance;
  16.         }
  17.        
  18.         public function WSClient()
  19.         {
  20.             super();
  21.         }
  22.     }
  23. }

Now, here is where the action happens..

Actionscript:
  1. public function getProductSizes(locationId:Number, lang:String = "EN"):Number
  2. {
  3.     var request:URLRequest = new URLRequest("http://nowhere.com");
  4.     request.method = URLRequestMethod.GET;
  5.  
  6.     var vars:URLVariables = new URLVariables();
  7.    
  8.     vars.locationId = locationId;
  9.     vars.lang = lang;
  10.     request.data = vers;
  11.  
  12.     var wrapper:Object = {
  13.         locationId : locationId,
  14.         lang : lang
  15.      };
  16.  
  17.     return runLoader(request, handleProductSizes, wrapper);
  18. }

This function is public, so it can be called by the object using this WSClient. It returns a number, the unique identifier of the request. First we create the URLRequest object pointing the url of your service. Then we assign GET method to it. Then we put all the variables inside of a URLVariables object, and assign it to the request. Then create the wrapper object, giving it certain params that could be useful later and call runLoader which does the magic for us.

You will notice that runLoader receives a reference to handleProductSizes which is actually a function that we need to define like so:

Actionscript:
  1. protected function handleProductSizes(evt:Event):void
  2. {
  3.     // get the wrapper
  4.     var wrapper:Object = getWrapper(evt.target as URLLoader);
  5.  
  6.     // convert received data to XML
  7.     var xml:XML = new XML(evt.target.data as String);
  8.  
  9.     // get the locationId from the wrapper
  10.     var locationId:Number = wrapper.locationId;
  11.  
  12.     // here you would digest the information into some kind of feed, like showed in Part 3 of the series
  13.     var feed:ProductSizeFeed = new ProductSizeFeed(xml.sizes[0]);
  14.  
  15.     // then dispatch some event, the event contains the requestId, so anybody listening to this event can know if it was their request ... or not.
  16.     dispatchEvent(new ProductSizeEvent(ProductSizeEvent.PRODUCT_SIZE_FEED_READY, feed, locationId, wrapper.id));
  17. }

As a bonus, here is the code for the ProductSizeEvent

Actionscript:
  1. package maax.events
  2. {
  3.     import maax.feeds.ProductSizeFeed;
  4.    
  5.     /**
  6.      * ...
  7.      * @author Martin Legris
  8.      */
  9.     public class ProductSizeEvent extends WSEvent
  10.     {
  11.         public static var PRODUCT_SIZE_FEED_READY:String = "product_size_feed_ready";
  12.        
  13.         protected var _feed:ProductSizeFeed;
  14.         public function get feed():ProductSizeFeed { return _feed; }
  15.        
  16.         public function ProductSizeEvent(type:String, feed:ProductSizeFeed, locationId:Number, requestId:Number)
  17.         {
  18.             _feed = feed;
  19.             super(type, locationId, requestId);
  20.         }
  21.     }
  22. }

Hope this helps! full source code... well you can ask; but this is straightforward, I encourage READING and TRYING and getting it to work. This is invaluable experience and cannot be bought or copy-pasted.

Cheers!

Martin



Related posts (automatically generated):

  1. Tutorial - Consuming REST web services in ActionScript 3 - Part 1
  2. Tutorial - Consuming REST web services in ActionScript 3 - Part 2
  3. Tutorial - Consuming REST web services in ActionScript 3 - Part 3
  4. Tutorial - AS3 & REST web services with RESTProxy - Part 1


Leave a Reply