jsonactionscript-3

How to post JSON data using Actionscript 3.0?


I have to work with webservices in Actionscript. I found the following code that allows me to use JSON URLs that implement only the GET method. However, it doesn't work for POST methods (doesn't even enter the "onComplete" method). I searched the net and was unable to find any answers. How can i "POST" JSON data using Actionscript 3.0?

package 
{
import flash.display.Sprite;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.events.*;
import com.adobe.serialization.json.JSON; 

public class DataGrab extends Sprite {

    public function DataGrab() {

    }

    public function init(resource:String):void {
            var loader:URLLoader = new URLLoader();
            var request:URLRequest = new URLRequest(resource);
            loader.addEventListener(Event.COMPLETE, onComplete);
            loader.load(request);
    }       

    private function onComplete(e:Event):void {
            var loader:URLLoader = URLLoader(e.target);
            var jsonData:Object = JSON.decode(loader.data);
            for (var i:String in jsonData)
            {
                trace(i + ": " + jsonData[i]);
            }
    }
}
}

Solution

  • You need to specify the method used with your URLRequest object. The default is GET. This could be a second argument to your init method:

    public function init(resource:String,method:String = "GET"):void {
        var loader:URLLoader = new URLLoader();
        var request:URLRequest = new URLRequest(resource);
        request.method = method;
        loader.addEventListener(Event.COMPLETE, onComplete);
        loader.load(request);
    }
    

    When you call this function you can use the static GET and POST properties of URLRequestMethod rather than just passing strings for a little bit of extra safety.