AS3 post xml ULRequest - actionscript-3

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.

Related

Sending data to a JSON with AS3

I've asked my client to share his database login and password but he can't give me full access to his database (security reason I suppose).
He told me to use a REST/JSON service that allows to post the data via this url with a specific key that allows him to identify all the datas coming from my app.
Here's what I did :
var urlRequest:URLRequest = new URLRequest("the_url_using JSON service");
urlRequest.method = URLRequestMethod.POST;
var urlvars: URLVariables = new URLVariables;
urlvars.observer_name = "Test Coco";
urlvars.observation_number = "5433";
trace("urlvars = "+urlvars);
urlRequest.data = urlvars;
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, onComplete);
urlLoader.load(urlRequest);
It's working, as it's sending the data, but the data format seems to be incorrect..
the url returns this error : "Observer name is Missing"
And the "trace (urlvars)" output :
urlvars = observer%5Fname=Test%20Coco&observation%5Fnumber=5433
So I think the problem come from the special character or something like that (as you can "observer_name" results by "observer%5Fname" and we can see a lot of %5")
Any idea how can I solve this ?
JSON string is a string representation of a generic object. Basically you go:
var anObject:Object =
{
"observer_name": "Test Coco",
"observation_number": 5433
};
or you can construct it
var anObject:Object = new Object;
anObject['observer_name'] = "Test Coco";
anObject['observation_number'] = 5433;
and then you convert it to String and attach to request
var jsonString:String = JSON.stringify(anObject);
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = jsonString;
Read more about it: https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/JSON.html
Keep in mind that I don't know the specifics of that REST server of yours and the code above just might not work as it is. I only explain how to send a JSON string as a POST request.

Flash as3 - API request with custom headers: POST but appears as GET (IOError #2032) [duplicate]

This question already has answers here:
URLRequest/URLLoader auto-converting POST request to GET
(2 answers)
Closed 7 years ago.
i have this file that makes an API request somewhere to retrieve JSON data.
The request needs to have 2 custom headers. I've read that custom headers require the request to be a POST.
I've read all the previous questions here and also on other sites, i think the code shows it pretty well... The "funny" part is that at some point i created a logger (environment: Tomcat) to see why it wasn't loading, and apparently the request i'm sending is a GET even if i've specified for it to be a POST...
Code
var url:String = "your_url_here";
var headers:Array = [
new URLRequestHeader("user-id","your_user-id"),
new URLRequestHeader("custom-auth","your_custom_auth_code"),
new URLRequestHeader("Accept","application/json")
];
var request:URLRequest = new URLRequest();
request.requestHeaders = headers;
request.method = URLRequestMethod.POST;
request.contentType = "application/json";
request.url = url;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener(Event.COMPLETE, decodeJSON);
loader.addEventListener(IOErrorEvent.IO_ERROR, handleError);
loader.load(request);
private function handleError(e:IOErrorEvent):void{
sometextcontainer.txt01.text = e.toString();
}
private function decodeJSON(e:Event) {
var Info:Object = JSON.parse(e.target.data);
// text fillers
}
The error: #2032 STREAM ERROR but i was 100% sure about the URL being correct, so i made a logger to actually see what was happening on the other side and surprise surprise... The request appears to be a GET!
What did i do wrong? Ideas?
Note1: i don't have sandbox security problems as i already placed Global exceptions;
Note2: i tried the request in REST with the custom headers (as POST) and it works (and the logger says i actually made a POST...)
Thanks for your kind help! :)
That made the trick.
I'm adding the code in order to make everyone understand it better and quicker. Basically, i added the following:
var datareq:URLVariables = new URLVariables();
datareq.dummyTest = "true";
request.data = datareq;`
So now it looks like:
var request:URLRequest = new URLRequest();
var datareq:URLVariables = new URLVariables();
datareq.dummyTest = "true";
request.data = datareq;
request.requestHeaders = headers;
request.method = URLRequestMethod.POST;
request.contentType = "application/json";
request.url = url;
Thanks for the help.

How to use a variable as part of an URL

I have a variable
var qstAccessCode:String = "default";
and a loader with URLRequest
var qst:XML;
var qstLoader:URLLoader = new URLLoader();
qstLoader.load(new URLRequest("http://dl.dropbox.com/u/44181313/Qaaps/Audio/" + qstAccessCode + ".qst"));
qstLoader.addEventListener(Event.COMPLETE, processQST);
function processQST(e:Event):void {
qst = new XML(e.target.data);
trace("QST loading");
}
I would like to use the value of qstAccessCode to complete the URL (so I can change the URL based on user input - if no input then use "default") but I get an error:
"1120: Access of undefined property qstAccessCode"
Is this to do with scoping? How can I complete the URL? Thanks in advance.
Edit: I haven't been able to get clear on this, so I'm also going to look at generating the complete URL from the user-input function and see if I get the URLRequest to pick it up as a variable. If there are any further comments on the original idea I will be very grateful to read them. Cheers.
Edit: #Moorthy I have qstAccessCode defined like this:
var qatAccessCode:String = "default";
var stageText:StageText = new StageText();
stageText.returnKeyLabel = ReturnKeyLabel.GO;
stageText.stage = this.stage;
stageText.viewPort = new Rectangle(225, 765, 200, 35 );
stageText.addEventListener(Event.CHANGE, onChange);
function onChange(e:Event):void
{
qatAccessCode = stageText.text;
trace(qatAccessCode);
}
It traces keyboard entry when I test movie (Air 3.2 for Android).
qstAccessCode should be defined in the same scope as the URLRequest.
You must defined property qstAccessCode like:
var qstAccessCode:string;
qstAccessCode's value is your url address.

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
}