2

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]);
            }
    }
}
}
S.Raaj Nishanth
  • 242
  • 2
  • 15

2 Answers2

4

I'm doing it with

import com.adobe.serialization.json.JSON;

var messages:Array = new Array ();  
messages.push ({"nombreArchivo":"value"});
messages.push ({"image":"value"});  

var vars: URLVariables = new URLVariables();
vars.data   = JSON.encode(messages);

var req: URLRequest = new URLRequest();
req.method      = URLRequestMethod.POST;
req.data        = vars;
req.url         = "crearIMG.php"

var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, handleServerResponse);
loader.load(req);
Javier Gutierrez
  • 549
  • 5
  • 16
4

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.

shanethehat
  • 15,460
  • 11
  • 57
  • 87
  • Heads up if you need to use Get with custom headers. Flash does not support this functionality. See https://stackoverflow.com/questions/223312/custom-headers-possible-with-urlrequest-urlstream-using-method-get/695890#695890 – haysclark May 11 '15 at 22:18