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 2

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

Hi Everyone,

the first part of this tutorial can be found here: Tutorial - Consuming REST web services in ActionScript 3 - Part 1.

Today I will continue on the exploration of consuming REST web services in ActionScript 3. We will cover possible errors first, then create a versatile web service client object which is easily adaptable to all your projects.

IMPORTANT NOTE

Yesterday in my exploration of the new YouTube Data API roll-out, I ran into a wall concerning PUT and DELETE requests. The method described in these tutorials doesn't permit those operations because of limitations in the URLRequest object. It actually throws exceptions if you try to put the .method parameter to anything other than GET or POST. I find this ridiculous. Completely ridiculous. The method of the HTTP Request is a simple string in the HTTP header, 3 or 4 characters long. Why not give us control over it? For Flex users, you can use the HTTPService class, but Flash users? Left to nada. I prefer not using Flex, it's BLOATED. More on that in another post..

Where we were

At the end of the last tutorial, we had the following code:

Actionscript:
  1. // we are still sending GET variables along..
  2. var request:URLRequest = new URLRequest("http://www.mydomain.com/feed/myfeed?query=youlike&start=34");
  3.  
  4. var loader:URLLoader = new URLLoader();
  5. loader.dataFormat = URLLoaderDataFormat.TEXT;
  6. request.method = URLRequestMethod.POST;
  7.  
  8. var variables:URLVariables = new URLVariables();
  9. // these can be anything, you choose!
  10. variables.vote = "yeah!";
  11. variables.id = 2193;
  12.  
  13. // assign the data to be sent by POST
  14. request.data = variables;
  15.  
  16. // add event listener
  17. loader.addEventListener(Event.COMPLETE, handleResults);
  18.  
  19. // send the request
  20. loader.load(request);

Then for the handler function, where we converted the results to XML

Actionscript:
  1. function handleResults(evt:Event):void
  2. {
  3.     var response:String = evt.target.data as String;
  4.     var xmlData:XML;
  5.     try
  6.     {
  7.         xmlData = new XML(response);
  8.     }
  9.     catch(error:TypeError)
  10.     {
  11.         trace("the response data was not in valid XML format");
  12.     }
  13. }

.

Handling Errors

So how many events do the URLLoader throw? And what do they do? Here is a summary :

  • "complete" flash.events.Event.COMPLETE - Dispatched after all the received data is decoded and placed in the data property of the URLLoader object.
  • "httpStatus" flash.events.HTTPStatusEvent.HTTP_STATUS - Dispatched if a call to URLLoader.load() attempts to access data over HTTP.
  • "ioError" flash.events.IOErrorEvent.IO_ERROR - Dispatched if a call to URLLoader.load() results in a fatal error that terminates the download.
  • "open" Flash.events.Event.OPEN - Dispatched when the download operation commences following a call to the URLLoader.load() method.
  • "progress" flash.events.ProgressEvent.PROGRESS - Dispatched when data is received as the download operation progresses.
  • "securityError" flash.events.SecurityErrorEvent.SECURITY_ERROR - Dispatched if a call to URLLoader.load() attempts to load data from a server outside the security sandbox.

I am mostly interested in "complete", "ioError", "securityError", and eventually for requests which return anything other than 200 (201 Created is one example), we need to catch the "httpStatus". So let's handle those new events..

Actionscript:
  1. // add the imports at the beginning
  2. import flash.events.IOErrorEvent;
  3. import flash.events.SecurityErrorEvent;
  4.  
  5. // ...
  6.  
  7. // "event"
  8. loader.addEventListener(Event.COMPLETE, handleResults);
  9.  
  10. // "ioError"
  11. loader.addEventListener(IOErrorEvent.IO_ERROR, handleIOError);
  12.  
  13. // "securityError"
  14. loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR , handleSecurityError);
  15.  
  16. // send the request
  17. loader.load(request);

For these new error event handlers, we implement the functions. What you do exactly inside those functions depends on the situation, you might want to display an error message, notify another service of the problem, or simply trace them to your output if you are in testing phase. This is what I will demonstrate now.

Actionscript:
  1. protected function handleIOError(evt:IOErrorEvent):void
  2. {
  3.     trace("handleIOError(" + evt.toString());
  4. }
  5.        
  6. protected function handleSecurityError(evt:SecurityErrorEvent):void
  7. {
  8.     trace("handleSecurityError("+evt.toString());         
  9. }

On with the Singleton

The idea of the Singleton design pattern is to create an object that can be easily accessible from anywhere in your code. You import it, then you do :

Actionscript:
  1. var mySingleton = MySingleton.getInstance();

and off you go. You will always deal with the same object as this pattern ensures you only have one instance of it. In my head a little bulb lights up and says: this is what you need! Here is the code we need to create our singleton:

Actionscript:
  1. package webservice
  2. {
  3.     import flash.net.URLRequestMethod;
  4.     import flash.net.URLVariables;
  5.    
  6.     import flash.events.Event;
  7.     import flash.net.URLLoader;
  8.     import flash.net.URLRequest;
  9.     import flash.net.URLLoaderDataFormat;
  10.     import flash.events.IOErrorEvent;
  11.     import flash.events.SecurityErrorEvent;
  12.  
  13.     public class WSClient
  14.     {
  15.         private static var _instance:YouTubeClient;
  16.  
  17.         public static function getInstance():YouTubeClient
  18.         {
  19.             if (_instance == null)
  20.                 _instance = new YouTubeClient();
  21.            
  22.             return _instance;
  23.         }
  24.  
  25.         public function WSClient()
  26.         {
  27.             // do nothing for now..
  28.         }
  29.  
  30.         public function runRequest(query:String, start:Number):void
  31.         {
  32.             // code for our request goes here..
  33.         }
  34.  
  35.         function handleResults(evt:Event):void
  36.         {
  37.             // result handling code goes here
  38.         }
  39.  
  40.         protected function handleIOError(evt:IOErrorEvent):void
  41.         {
  42.             // ioerror handling code goes here
  43.         }
  44.        
  45.         protected function handleSecurityError(evt:SecurityErrorEvent):void
  46.         {
  47.             // securityerror handling code goes here
  48.         }
  49.     }
  50. }

Now, it is impossible to have a private or protected constructor. Hence some people came up with nifty tricks to enfore the Singleton; personally I work alone on most projects and don't need to. You can search on google for "as3 singleton" and you'll find good examples.

To use the WSClient we would do

Actionscript:
  1. import webservice.WSClient;
  2.  
  3. var client:WSClient = WSClient.getInstance();
  4.  
  5. client.runRequest();

But then you might ask, how does my calling code know when the results are ready?

Dispatching Events when the data comes in..

Once the data is handled by our handleResults function, it would be ideal if the WSClient would dispatch an event, telling the calling code that the results are ready to be used. We will therefore derive from EventDispatcher (some people prefer composition) this way:

Actionscript:
  1. package webservice
  2. {
  3.     // other imports go here...
  4.  
  5.     import flash.events.EventDispatcher;
  6.  
  7.     public class WSClient extends EventDispatcher
  8.     {
  9.         // class implementation goes here..
  10.     }
  11. }

Now for the dispatching of the event:

Actionscript:
  1. // inside of the handleResults function
  2.     function handleResults(evt:Event):void
  3.     {
  4.         var response:String = evt.target.data as String;
  5.         var xmlData:XML;
  6.         try
  7.         {
  8.             xmlData = new XML(response);
  9.            
  10.             // we dispatch an event to notify the results are in..
  11.             dispatchEvent(new Event("results", false, false));
  12.         }
  13.         catch(error:TypeError)
  14.         {
  15.             trace("the response data was not in valid XML format");
  16.         }
  17.     }

Our caller code can now be aware that the data is ready, but how to access it?

Custom Events

The approach I like is to create custom event classes. One such event class is used to notify the caller code that the data is ready and transport the data to it. To do this, we need to derive from the flash.event.Event class. We will define one event type, add a property to contain the data, and define a getter to access it:

Actionscript:
  1. package events
  2. {
  3.     import flash.events.Event;
  4.  
  5.     public class ResultEvent extends Event
  6.     {
  7.         public static const RESULTS_RECEIVED:String = "results_received";
  8.  
  9.         // in our case the data is of XML type..
  10.         protected var _data:XML;
  11.  
  12.         // the getter
  13.         public function get data():XML
  14.         {
  15.             return _data;
  16.         }
  17.  
  18.         public function ResultEvent(type:String, data:XML)
  19.         {
  20.             // initialize the event
  21.             super(type);
  22.  
  23.             // keep reference to the data
  24.             _data = data;
  25.         }      
  26.     }
  27. }

On with dispatching the custom event:

Actionscript:
  1. // import it
  2.     import events.ResultEvent;
  3.  
  4.     // inside of the handleResults function
  5.     function handleResults(evt:Event):void
  6.     {
  7.         var response:String = evt.target.data as String;
  8.         var xmlData:XML;
  9.         try
  10.         {
  11.             xmlData = new XML(response);
  12.            
  13.             // we dispatch the custom event which will carry the data for us to all listeners..
  14.             dispatchEvent(new ResultEvent(ResultEvent.RESULTS_RECEIVED, xmlData));
  15.         }
  16.         catch(error:TypeError)
  17.         {
  18.             trace("the response data was not in valid XML format");
  19.         }
  20.     }

Back to the caller code:

Actionscript:
  1. import webservice.WSClient;
  2. import events.ResultEvent;
  3.  
  4. var client:WSClient = WSClient.getInstance();
  5. client.addEventListener(ResultEvent.RESULTS_RECEIVED, processResult);
  6. client.runRequest("beauty", 10);
  7.  
  8. protected function processResult(evt:ResultEvent):void
  9. {
  10.     // get our results..
  11.     var data:XML = evt.data;
  12.    
  13.     // do something with it!
  14. }

Looks like there will be a third installment! I will describe how to handle situations were multiple callers use the same function: how to ensure the results you are getting are yours and not the results from somebody else's request. I will also standardize certain tasks inside of the WSClient.

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 3
  3. Tutorial - AS3 & REST web services with RESTProxy - Part 1
  4. Tutorial - Consuming REST web services in ActionScript 3 - Part 4


8 Responses to “Tutorial - Consuming REST web services in ActionScript 3 - Part 2”

  1. intense creativity » Tutorial - Consuming REST web services in ActionScript 3 - Part 1 says:

    [...] the next installment, I demonstrate how I wrap all this functionality in a [...]

  2. Miguel says:

    very good I waiting for this long time ago and I cannot wait for the third part, thanks!!!

  3. intense creativity » Tutorial - Consuming REST web services in ActionScript 3 - Part 3 says:

    [...] This is the third installment of the series, you can find the first two here: Part 1 - http://blog.martinlegris.com/?p=87 Part 2 - http://blog.martinlegris.com/?p=90 [...]

  4. Vivian says:

    Any news on the rare HTTPService/URLRequest implementation and other HTTP methods like PUT/HEAD? Do you know if something changed with Flash Player 10? I could find a bug report on Adobe’s JIRA yet.

  5. James says:

    Thanks for this, it is great! But I’m stuck. Maybe I’m just not getting it, but what is the YouTubeClient() all about? I assume it has to do with the YouTube Data API.

    What if I wasn’t using that, what would I put there instead?

    Thanks, James

  6. James says:

    Disregard the previous message! I’m an idiot.

  7. Jeff says:

    You could always use the HTTP Service class from inside Flash.

    http://www.jeffguthrie.com/httpservice-and-arraycollection-in-flash-cs4

    I like this tutorial though… Very helpful.

  8. Simon Janssen says:

    Is there a sourcecode example available? I am trying to implement a webservice call in AS3. Thnks in advance

Leave a Reply