GET request Flex / Actionscript 3 - actionscript-3

Struggling to find any documentation to do a simple GET request to a URL to return JSON in Actionscript / Flex.
Anyone know

Use the URLLoader API.
var myJSON :Object; //listing as per "key:" with "value"
var str_JSON: String = ""; //if you need text String not data Object
var siteloader :URLLoader = new URLLoader( new URLRequest( your_URL ) );
siteloader.addEventListener(Event.COMPLETE, whenSiteLoaded);
function whenSiteLoaded( evt :Event ) :void
{
myJSON = JSON.parse(evt.target.data); //get into Object
str_JSON = evt.target.data; //get into String
//... any other code
}
You should add to the above the listeners for error conditions (eg: a "file not found" situation)

Related

JSON encoding for Flash Player 11 and AIR 3.0

I have the following code:
thinkGearSocket = new Socket();
var configuration : Object = new Object();
configuration["enableRawOutput"] = true;
configuration["format"] = "Json";
thinkGearSocket.connect("127.0.0.1", 13854);
thinkGearSocket.addEventListener(ProgressEvent.SOCKET_DATA, dataHandler);
thinkGearSocket.writeUTFBytes(JSON.encode(configuration));
It works for flash player 10 but for flash player 11 I get an error saying:
1061: Call to a possibly undefined method encode though a reference with static type flash.net:socket
I had the same error for the decoding with this:
private function dataHandler(e : ProgressEvent){
//read data from the socket
var packetString : String = thinkGearSocket.readUTFBytes(thinkGearSocket.bytesAvailable);
thinkGearSocket.flush();
//split the data into an array
var packets : Array = packetString.split(/\r/);
var data:Object;
//iterate through array elements
for each (var packet:String in packets){
//sometimes the packet is empty
if(packet != "") {
try {
data = JSON.decode(packet);
//trace(packet);
} catch ( jError: JSONParseError) {
// do exception handling here
label1.text = jError.text;
}
But I changed:
data = JSON.decode(packet);
to:
data = JSON.parse(packet);
and now I don't get an error for that part. how do I fix the encoding part for Flash player 11 and AIR 3.0?
You need to use the stringify method instead of encode for Flash 11 or greater.
stringify(value:Object, replacer:* = null, space:* = null):String
You can see more information in the AS3 livedocs for stringify.

How to create an object of specific type from JSON in Parse

I have a Cloud Code script that pulls some JSON from a service. That JSON includes an array of objects. I want to save those to Parse, but using a specific Parse class. How can I do it?
Here's my code.
Parse.Cloud.httpRequest({
url: 'http://myservicehost.com',
headers: {
'Authorization': 'XXX'
},
success: function(httpResponse) {
console.log("Success!");
var json = JSON.parse(httpResponse.text);
var recipes = json.results;
for(int i=0; i<recipes.length; i++) {
var Recipe = Parse.Object.extend("Recipe");
var recipeFromJSON = recipes[i];
// how do i save recipeFromJSON into Recipe without setting all the fields one by one?
}
}
});
I think I got it working. You need to set the className property in the JSON data object to your class name. (Found it in the source code) But I did only try this on the client side though.
for(int i=0; i<recipes.length; i++) {
var recipeFromJSON = recipes[i];
recipeFromJSON.className = "Recipe";
var recipeParseObject = Parse.Object.fromJSON(recipeFromJSON);
// do stuff with recipeParseObject
}
Example from this page https://parse.com/docs/js/guide
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.save({
score: 1337,
playerName: "Sean Plott",
cheatMode: false
}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and message.
}
});
IHMO this question is not a duplicate of How to use Parse.Object fromJSON? [duplicate]
In this question the JSON has not been generated by the Parse.Object.toJSON function itself, but comes from another service.
const object = new Parse.Object('MyClass')
const asJson = object.toJSON();
// asJson.className = 'MyClass';
Parse.Object.fromJSON(asJson);
// Without L3 this results into:
// Error: Cannot create an object without a className
// It makes no sense (to me) why the Parse.Object.toJSON is not reversible

AS3 post xml ULRequest

I am having trouble posting an xml file with the URLLoader.
After it loads it seems that there is no XML attached to the request, could any
please clarify what i am doing wrong here (banging head against the wall)
// code
private function postXmlFiles():void
{
var a:XML = new XML(new EmbeddedXML());
var r:URLRequest = new URLRequest("http://vms.api.apic.co/rest/v3/addmedia");
r.data = a;
r.method = URLRequestMethod.POST;
r.contentType = "text/xml";
l = new URLLoader();
l.dataFormat = URLLoaderDataFormat.TEXT;
// Handlers
l.addEventListener(Event.COMPLETE, on_complete);
l.load(r);
}
private function on_complete(e : Event):void
{
trace('loaded!:' + l.data); // this is returning "loaded!: No xml file attached to the request."
}
I tested your code, replacing one string:
var a:XML = new XML("<test/>");
Trace output changed, indicating l.data field actually contains something.
I also used debugging proxy, and examined request body, it does contained my <test/> string.
You should test your new EmbeddedXML() call to see what it returns.

Assign a request timeout for adobe air URLRequest and get the response without using eventListner

Below code is used to read a file in the disk and upload as 1MB chunks to a php server via adobe AIR application. It iterates the do/while loop till the end of the file and uploading part is handled by function getConnection. The servers returns an XML as the response. With the eventListeners currently it goes to function onRequestComplete when it receives the response. Because of that issue current code exits the loop when it receives the response from the server. Is there any way that I can get the response of the request send by the function getConnection when it calling inside function startUpload ? also how can I define the request timeout for this single requests?
private function startUpload():void {
var localFilePath:String =localFilesToUpload[currentUploadedVideoIndex].file.nativePath;
var filePathArray = localFilePath.split("/");
var uploadedFile:File = new File(localFilePath);
var fileSize:Number = uploadedFile.size;
var fileName:String = filePathArray[filePathArray.length-1];
var fileId:String = "10";
var index:Number=0;
var chunkSize:Number=1024*1204;
var size:Number=chunkSize;
var serverPath:String = "http://myurl/rests";
//encode username and password
var userName:String="myusername";
var password:String="mypassword";
var encoder:Base64Encoder = new Base64Encoder();
encoder.insertNewLines=false;
encoder.encode(userName+":"+password);
var urlLoader:URLLoader=new URLLoader();
urlLoader.dataFormat=URLLoaderDataFormat.TEXT;
urlLoader.addEventListener(Event.COMPLETE,onRequestComplete);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR,onResponceFail);
var urlRequest:URLRequest = new URLRequest(serverPath);
urlRequest.method=URLRequestMethod.POST;
do{
//if this is true file must be uploaded as a chunk
if(fileSize>chunkSize){
if((index+size)>fileSize){ // if true this is the final chunk of the file.
size = fileSize-index; // take the remaining size of the file
}
}else{
size = fileSize; //this file can be uploaded directly
}
//read the bytes from the file in the specified location
var buff:ByteArray = new ByteArray();
var uploadedFileStream:FileStream = new FileStream();
uploadedFileStream.open(uploadedFile,FileMode.READ);
uploadedFileStream.readBytes(buff);
uploadedFileStream.close();
urlRequest.data=buff;
//add the http headers to the file part and send
this.getConnection(urlRequest, urlLoader,encoder.toString(),fileSize,index,chunkSize,fileName,fileId,buff);
}while(index<fileSize)
}
}
private function getConnection(urlRequest:URLRequest, urlLoader:URLLoader ,authString:String, fileSize:Number, index:Number, chunkSize:Number, fileName:String, fileId:String, requestBody:ByteArray):void{
//creates the relevent HTTP heaaders and assigned to parameters
try{
urlRequest.requestHeaders = parameters;
urlLoader.load(urlRequest);
}catch(error:Error){
Alert.show(error.message);
}
}
private function onRequestComplete(event:Event):String{
var loader:URLLoader = URLLoader(event.target);
Alert.show(loader.data,"Result");
}
private function onResponceFail(event:FaultEvent):void{
Alert.show(event.message.toString(),"Fault");
}
In order to achieve this, you should check if operation is finished in onRequestComplete instead:
Pseudo code just to get you going:
function startUpload()
{
// prepare big file
...
// then start the uploading
sendNextChunk();
}
function sendNextChunk()
{
// grab the next chunk
...
// and send it
getConnection(...);
}
function onRequestComplete()
{
// is there more chunks ?
if (...more chunks?)
sendNextChunk();
else
trace("All chunks uploaded");
}
Hope that helps,
Adnan

How to get Facebook post id with Facebook-Actionscript SDK?

After I upload a photo on a desktop facebook application i need to store it's post id in a database. From the facebook ActionScript SDK documentation:
api() method
public static function api(method:String, callback:Function, params:* = null, requestMethod:String = GET):void
Makes a new request on the Facebook Graph API.
Parameters [...]
callback:Function — Method that will be called when this request is complete The handler must have the signature of callback(result:Object, fail:Object); On success, result will be the object data returned from Facebook. On fail, result will be null and fail will contain information about the error.
So I implemented my callback function as follows:
protected function handleUploadComplete(response:Object, fail:Object):void{
status = (response) ? 'Success' : 'Error';
var file:File = File.desktopDirectory.resolvePath("Log.txt");
var stream:FileStream = new FileStream();
stream.open(file, FileMode.WRITE);
stream.writeUTFBytes(response.toString());
stream.close();
}
The problem is that response or response.toString() both return "[object Object]", and I was hoping for something more like "id: somenumber".
What am I doing wrong?
If everything has worked the response will contain a property called id that is your post ID. Otherwise it will be null and the fail object will be populated.
protected function handleUploadComplete(response:Object, fail:Object):void
{
var status:Boolean = response != null;
if(status) var id:String = response.id;
//do whatever you want
}