How to post JSON data using Actionscript 3.0? - json

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]);
}
}
}
}

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.

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);

Related

Passing variables from actionscript 3 to actionscript 2

I have a swf written in AS3 which loads an AS2 swf.
AS3 code:
var url:String = "as2.swf?myvar=hello";
var spURL:Array = url.split("?");
var urlVars:URLVariables = new URLVariables();
urlVars.decode(spURL[1]);
var req:URLRequest = new URLRequest( spURL[0] );
req.data = urlVars;
req.method = URLRequestMethod.GET;
AS2 code:
trace(_root.myvar);
but nothing traced!
I found solution to my question.
Full source code bellow
AS3: with a movieclip named "as2btn" and a text field named "as3_log". The publish class name is "main_as3"
package {
import flash.display.*;
import flash.events.*;
import flash.net.*;
public class main_as3 extends MovieClip {
public var ld:Loader;
public function main_as3() {
// constructor code
this.as2btn.addEventListener(MouseEvent.MOUSE_DOWN, as2Load);
this.logMessage("Initialized!");
}
public function logMessage(msg:String)
{
this.as3_log.appendText("AS3: " + msg + "\n");
}
public function as2Load(evt:MouseEvent)
{
if (this.ld) {
this.ld.unloadAndStop();
this.ld = null;
}
var url:String = "as2.swf?myvar=1rewr&myvar2=1234";
var spURL:Array = url.split("?");
var urlVars:URLVariables = new URLVariables();
urlVars.decode(spURL[1]);
var req:URLRequest = new URLRequest(spURL[0]);
req.data = urlVars;
req.method = URLRequestMethod.GET;
this.ld = new Loader();
this.ld.load(req);
addChild(this.ld);
}
}
}
AS2: with a movieclip linkage identifier "main" and class name "main_as2" includes a text field named "as2_log"
class main_as2 extends MovieClip
{
var _parent;
function main_as2()
{
super();
this.gotoAndStop(1);
this.logMessage("Initialized!");
this.logMessage("_parent.myvar: " + _parent.myvar);
}
function logMessage(msg:String)
{
this["as2_log"].text = this["as2_log"].text + "AS2: " + msg + "\n";
}
}

ActionScript 3.0 web scraper works in flash, but not browser

so I have this issue. I recently made a flash webscraper to grab a video source link. It works in flash, however when I test in the browser I only get a blank canvas... It does not work. I have no idea as to what the problem is... I just started learning actionscript today, so I'm far from the greatest at it.
import flash.net.*
import flash.events.*;
import flash.display.*;
var theUrl = "http://www.sockshare.com/file/384F14398D224634";
firstStep();
function firstStep() {
var urlReq: URLRequest = new URLRequest(theUrl);
urlReq.method = URLRequestMethod.POST;
var loader: URLLoader = new URLLoader(urlReq);
loader.addEventListener(Event.COMPLETE, onSuccess);
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.load(urlReq);
function onSuccess(e: Event): void {
var theContents1: String = String(loader.data);
var pattern1: RegExp = /<input type="hidden" value="(?P<innertext>.*?)" name="hash">/;
var result1 = pattern1.exec(theContents1);
goToSecond(result1.innertext);
}
}
function goToSecond(hash: String) {
var urlReq2: URLRequest = new URLRequest(theUrl);
urlReq2.method = URLRequestMethod.POST;
var urlVars2: URLVariables = new URLVariables();
urlVars2.hash = hash;
urlVars2.confirm = 'Continue+as+Free+User';
urlReq2.data = urlVars2;
var loader2: URLLoader = new URLLoader(urlReq2);
loader2.addEventListener(Event.COMPLETE, onSuccess2);
loader2.dataFormat = URLLoaderDataFormat.VARIABLES;
loader2.load(urlReq2);
function onSuccess2(e: Event): void {
var theContents2: String = String(loader2.data);
var pattern: RegExp = /playlist%3A%20%27%2F(?P<innertext>.*?)%27%2C%0D%0A%09plugins/;
var result = pattern.exec(theContents2);
var linkp1: String = "http://www.sockshare.com/" + unescape(result.innertext);
finalStep(linkp1);
}
}
function finalStep(finalUrl: String) {
var urlReq3: URLRequest = new URLRequest(finalUrl);
urlReq3.method = URLRequestMethod.POST;
var loader3: URLLoader = new URLLoader(urlReq3);
loader3.addEventListener(Event.COMPLETE, onSuccess3);
loader3.dataFormat = URLLoaderDataFormat.TEXT;
loader3.load(urlReq3);
function onSuccess3(e: Event): void {
var theContents3: String = String(loader3.data);
var pattern2: RegExp = /<media:content url="(?P<innertext>.*?)" type="/;
var result2 = pattern2.exec(theContents3);
var finalLink: String = result2.innertext;
trace(finalLink);
mainText.text = finalLink;
}
}
It's sandbox problem, read here, if you'll publish as standalone (ex: Air) project it would work

action script 3.0 import fla with xml

i want import fla movie from xml. i can't make it. Thank for help.
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.text.engine.TabAlignment;
import flash.net.URLRequest;
import flash.media.Sound;
//i create timer for sound.
var tmr:Timer=new Timer(1000,1);
tmr.addEventListener(TimerEvent.TIMER, sesiBaslat);
function sesiBaslat(evt:TimerEvent){
var yol:URLRequest=new URLRequest("../../../sound/aaa/1/1/1.mp3");
var ses:Sound=new Sound();
ses.load(yol);
ses.play();
}
tmr.start();
//i was use this code in old times
/*var vid:Video = new Video(1600, 910);
flvPlaceHolder.addChild(vid);
addChild(flvPlaceHolder);
flvPlaceHolder.x = stage.stageWidth/2-vid.width/2;
flvPlaceHolder.y = stage.stageHeight/2-vid.height/2;
var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(nc);
vid.attachNetStream(ns);
var listener:Object = new Object();
listener.onMetaData = function(evt:Object):void {};
ns.client = listener;
ns.play("fla/683-bak.flv");
*/
//now i want to write this format now,because i want to make it dynamic
var veriler:XML;
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, XMLokundu);
loader.load(new URLRequest("../../../xml/aaa/1/1/1.xml"));
function XMLokundu(e:Event):void{
veriler= new XML(e.target.data);
var loader1:Loader = new Loader();
loader1.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
loader1.load(new URLRequest(veriler.animasyonlar.animasyon[1].yolu));
//This blog was made a import sound,image etc. but doesnt work from fla
function imageLoaded(e:Event):void {
var flvPlaceHolder:MovieClip = new MovieClip();
var vid:Video = new Video();
e.target.content.smoothing = true;
addChild(loader1);
loader1.x = veriler.animasyonlar.animasyon[1].xkor;
loader1.y = veriler.animasyonlar.animasyon[1].ykor;
loader1.width = veriler.animasyonlar.animasyon[1].width;
loader1.height = veriler.animasyonlar.animasyon[1].height;
}
}
/*
//XML FİLE
//This is my xml file
<animasyonlar>
<animasyon>
<first>sound/16/1153.mp3</first>
<ikincises>sound/16/1154.mp3</ikincises>
<ucuncuses>sound/16/1151.mp3</ucuncuses>
<dorduncuses>sound/16/1152.mp3</dorduncuses>
<yolu>../../../../bbb/7/fla/683-look.flv</yolu> 1.fla way
<xkor>800</xkor> 2.x value
<ykor>100</ykor> 3.y value
<width>50%</width>
<height>50%</height>
</animasyon>
</animsyonlar>
Your XML is not formatted properly because your closing tag is missing the 2nd "a".
<animasyonlar>
...
</animsyonlar>

AIR: how to use FileReference.upload() with POST-based web services (AS3)

I can't seem to get this little AIR app I'm making to work right. There is a single button on the stage, and when the user presses it they are presented with a file browser (FileReference.browse() function). When they select an image file, I want the image to be uploaded to the site imgur.com (http://www.api.imgur.com for those interested).
I'm getting a response from imgur, so I know my app is connecting, but it's returning an error, "No image data was sent to the upload API". Any help is greatly appreciated! (Also I do have an API key, just removed it from this post for obvious reasons :) )
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.net.*;
import flash.utils.ByteArray;
public class Document extends MovieClip
{
//file browser var
var myFileReference:FileReference = new FileReference();
//file loader var
private var loader:URLLoader;
//string constants
private const API_KEY:String = "******REMOVED*******";
private const UPLOAD_URL:String = "http://api.imgur.com/2/upload.xml";
public function Document()
{
// constructor code
browse_btn.addEventListener(MouseEvent.CLICK, browse);
}
function browse(e:MouseEvent)
{
var imagesFilter:FileFilter = new FileFilter("Images", "*.jpg;*.gif;*.png");
myFileReference.browse([imagesFilter]);
myFileReference.addEventListener(Event.SELECT, selectHandler);
myFileReference.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, responseHandler);
}
function selectHandler(e:Event):void
{
var vars:String = "?key=" + API_KEY + "&name=name&title=title";
var params:URLVariables = new URLVariables();
params.date = new Date();
var request:URLRequest = new URLRequest(UPLOAD_URL + vars);
//request.contentType = "application/octet-stream";
request.contentType = "multipart/form-data";
request.method = URLRequestMethod.POST;
request.data = params;
myFileReference.upload(request);
try
{
myFileReference.upload(request);
}
catch (error:Error)
{
trace("Unable to upload file.");
}
}
function responseHandler(e:DataEvent):void
{
trace("responseHandler() initaialized");
var res:XML = XML(e.data);
trace(res);
}
}
}
there's actually an example for AS3 on their site:
package
{
import com.adobe.images.PNGEncoder;
import flash.display.BitmapData;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.SecurityErrorEvent;
import flash.events.IOErrorEvent
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;
public class ImgurExample
{
private var loader:URLLoader;
private const API_KEY:String = "<api key>";
private const UPLOAD_URL:String = "http://api.imgur.com/2/upload.xml";
public function ImgurExample() {
loader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, onCookieSent);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
// Create a bitmapdata instance of a movieclip on the stage.
var mc:MovieClip;
var b:BitmapData = new BitmapData(mc.width, mc.height, true);
b.draw(mc);
var png:ByteArray = PNGEncoder.encode(b);
var vars:String = "?key=" + API_KEY + "&name=name&title=title";
var request:URLRequest = new URLRequest(UPLOAD_URL + vars);
request.contentType = "application/octet-stream";
request.method = URLRequestMethod.POST;
request.data = png; // set the data object of the request to your image.
loader.load(request);
}
// privates
private function onSend(e:Event):void {
var res:XML = new XML(unescape(loader.data));
trace(res);
}
private function onIOError(e:IOErrorEvent):void {
trace("ioErrorHandler: " + e);
// Handle error
}
private function onSecurityError(e:SecurityErrorEvent):void {
trace("securityErrorHandler: " + e);
// handle error
}
}
}
http://api.imgur.com/examples

AS3 - I can't get a string value returned from a function

AS3 code, from a sample, I want to have the value in the string 'location' available to other parts of the main program. It returns fine in the completed handler, but how do I make it available to the first part?
package {
import flash.display.MovieClip;
import flash.display.MovieClip;
import flash.events.*
import flash.net.*;
import flash.net.URLVariables;
public class turl extends MovieClip {
public var location:String = new String();
public function turl() {
// constructor code
var variables:URLVariables = new URLVariables();
variables.url = String("xxxxxxxxx");
sendAndLoad("xxxxxxxx", variables)
// THIS TRACE WILL NOT DISPLAY THE LOCATION _ A TINY URL
trace("TinyURL: " + location);
}
function sendAndLoad(url:String, _vars:URLVariables ):void {
var request:URLRequest = new URLRequest(url);
var _urlloader:URLLoader = new URLLoader();
_urlloader.dataFormat = URLLoaderDataFormat.TEXT;
request.data = _vars;
request.method = URLRequestMethod.POST;
_urlloader.addEventListener(Event.COMPLETE, handleComplete);
_urlloader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
_urlloader.load(request);
}
function handleComplete(event:Event):void {
var loader:URLLoader = URLLoader(event.target);
location = loader.data;
trace("TinyURL: " + location);
}
function onIOError(event:IOErrorEvent):void {
trace("Error loading URL.");
}
}
}
package
{
import flash.display.MovieClip;
import flash.display.MovieClip;
import flash.events.*
import flash.net.*;
import flash.net.URLVariables;
public class turl extends MovieClip
{
public static var Location:String;
public function turl() {
// constructor code
var variables:URLVariables = new URLVariables();
variables.url = String("http://www.designscripting.com");
sendAndLoad("http://tinyurl.com/api-create.php", variables)
// THIS TRACE WILL NOT DISPLAY THE LOCATION _ A TINY URL
trace("TinyURL: " + Location);
}
function sendAndLoad(url:String, _vars:URLVariables ):void
{
var request:URLRequest = new URLRequest(url);
var _urlloader:URLLoader = new URLLoader();
_urlloader.dataFormat = URLLoaderDataFormat.TEXT;
request.data = _vars;
request.method = URLRequestMethod.POST;
_urlloader.addEventListener(Event.COMPLETE, handleComplete);
_urlloader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
_urlloader.load(request);
}
function handleComplete(event:Event):void {
var loader:URLLoader = URLLoader(event.target);
Location= loader.data;
trace("TinyURLss: " + Location);
}
function onIOError(event:IOErrorEvent):void {
trace("Error loading URL.");
}
}
}
static variable Location holds your String value and you can get this String value
anywhere in class and outside the class.
The trace statement in the constructor doesn't work because that trace happens immediately after the data request is made, before the data has been downloaded and location has been set. The constructer is meant for setting the initial conditions of an object. The only way to make the result of the data request immediately available to the constructor is to pass it in directly, but I think this would defeat the point of the class.
public function TURL(value:String)
{
location = value;
// Now this will work like you think.
trace("TinyURL: " + location);
}
I'm guessing you have other objects relying on this TURL class having a proper location. If that's the case, have the TURL class dispatch an event when it sets the location variable, indicating that it is ready to be used.
function handleComplete(event:Event):void
{
var loader:URLLoader = URLLoader(event.target);
location = loader.data;
dispatchEvent(new Event(Event.COMPLETE));
}
Tested and working!
var turl:Turl = new Turl("http://www.designscripting.com");
Once the URL has been received you can access it by trace(turl.loc);
package {
import flash.display.MovieClip;
import flash.events.*
import flash.net.*;
import flash.net.URLVariables;
public class Turl extends MovieClip {
public var loc:String;
public function Turl(urlToEncode:String):void {
var variables:URLVariables = new URLVariables();
variables.url = String(urlToEncode);
sendAndLoad("http://tinyurl.com/api-create.php", variables);
}
//2. send the request for the URL
private function sendAndLoad(url:String, _vars:URLVariables ):void {
var request:URLRequest = new URLRequest(url);
request.data = _vars;
request.method = URLRequestMethod.POST;
var _urlloader:URLLoader = new URLLoader(request);
_urlloader.dataFormat = URLLoaderDataFormat.TEXT;
_urlloader.addEventListener(Event.COMPLETE, handleComplete, false, 0, true);
_urlloader.addEventListener(IOErrorEvent.IO_ERROR, onIOError, false, 0, true);
_urlloader.load(request);
}
//3. handle the response. Only accessible once the response has been received.
private function handleComplete(event:Event):void {
event.target.removeEventListener(Event.COMPLETE, handleComplete);
event.target.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
loc = event.target.data;
trace("loc = "+event.target.data);
}
function onIOError(event:IOErrorEvent):void {
event.target.removeEventListener(Event.COMPLETE, handleComplete);
event.target.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
trace("Error loading URL.");
}
}
}