Can AS3 handle HTTP errors with Payloads? - actionscript-3

I'd like to implement a RESTful API which returns HTTP error codes when needed. Can ActionScript 3 handle an HTTP error code (404, 500) response which contains a JSON message in its payload?
Are there any good references that I can use as feedback for our in-house Flash front-end team?

I've been struggling with this too. It seems that the answer is "no", AS3 cannot.
I have, intermittently, seen data come in through IOErrorEvent.currentTarget.data, but I am not able to consistently reproduce this.

You probably can do URLRequest and then handle the HTTP status
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("XMLFile.xml");
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
private function httpStatusHandler(event:HTTPStatusEvent):void {
trace("httpStatusHandler: " + event);
}
loader.load(request);
check the complete example :
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLRequest.html
you can add dispatcher.addEventListener(Event.COMPLETE, completeHandler); to find out whats coming back.

Related

Get location from the URLLoader?

How to get location from the URLLoader in AS3 or haxe?
What I have:
private function Auth():Void {
_url = "https://my_url.com";
request = new URLRequest(_url);
request.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
loader.load(request);
loader.addEventListener(Event.COMPLETE, fAuthAnswer);
}
private function fAuthAnswer(e:Event):Void {
trace(e.target.data);
}
And when the event is complete, i see the HTML code of the loaded page.
But I need to get a loaded URL, because site is redirected me and add auth information in URL. And i need to get it.
Help, please :)
PS I use haxe, so in my way I can't use stagewebview.
PPS Sorry for my English.
Listen for flash.events.HTTPStatusEvent http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLLoader.html#event:httpResponseStatus.
It has a property responseURL.

How do you read and write http headers in ActionScript?

Is it even possible to both read and write http headers in actionscript?
Hmm... ok setting them doesn't seem to be a problem.
Pretty straight forward, you just add and array of URLRequestHeader objects to the URLRequest object.
var req:URLRequest = new URLRequest();
var someheader:URLRequestHeader = new URLRequestHeader( "Connection", "OK" );
req.requestHeaders = [someheader];
However, you can't read them in the regular FlashPlayer. This can be done in AIR and Flash Lite on using the requestHeader property on the HTTPStatusEvent.
var loader:URLLoader = new URLLoader();
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
private function onStatus( e:HTTPStatusEvent ) : void
{
var headers:Array = e.requestHeaders; // only available in FlashLite and AIR
}
This is kinda weird.

AS3 POST Request sending as a GET

When trying to send a POST request to an ASP.NET asmx web service I am seeing (in Charles and Firebug) it go through as a GET.
Here is my AS3
public function save(page:SharedPageVO, callback :Function = null): void {
var req:URLRequest = new URLRequest( "service.asmx/CreateSharedPage" );
req.data = page;
req.method = URLRequestMethod.POST;
if (callback != null)
{
//handle removing the event here instead of there
this.complete = callback;
DataService.instance.addEventListener(Event.COMPLETE, onComplete);
}
DataService.instance.load( req );
}
public var complete:Function;
private function onComplete(e:Event)
{
if (complete != null) complete(e);
complete = null;
DataService.instance.removeEventListener(onComplete);
}
This seems to be an issue with flash as it is happening before it even goes to the server. I have uploaded this to a testing server and I still see it come through as a GET. Any help would be appreciated. Thanks.
From actionscript LR (URLRequest class, method property):
Note: If running in Flash Player and the referenced form has no body, Flash Player automatically uses a GET operation, even if the method is set to URLRequestMethod.POST. For this reason, it is recommended to always include a "dummy" body to ensure that the correct method is used.
Are you using that "dummy" body?

AS3 URLLoader throwing URL not found, but is connecting successfully

Okay getting some weirdness. I have a simple URLLoader in AS3 that loads an external XML document. It's loading just fine, I get a correct 302 Not Modified response in Charles, however flash tells me:
"URL Not Found"
Here is the relevant code:
//=============================================================================================
public function openXML(name:String):void { //decides what XML data feed and opens it
//=============================================================================================
var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();
//add event listener to URLLoader to call closeXML upon completion
xmlLoader.addEventListener(Event.COMPLETE, closeXML);
xmlLoader.load(new URLRequest("http://www.gessnerengineering.com/projects"));
//=========================================================
function closeXML(e:Event):void {
//=========================================================
xmlData = new XML(xmlLoader.data);
xmlLoader.removeEventListener(Event.COMPLETE, closeXML);
drawPage(name, xmlData);
}
}
The problem line according to the debugger is at:
xmlLoader.load(new URLRequest("http://www.gessnerengineering.com/projects"));
I've verified that I can browse to the URL via my browser and cURL, and Charles says that my SWF can and IS successfully accessing it too. However I still get this URL Not Found error. According to the Flash Actionscript 3 documentation, this is the absolute correct way to use URLLoader to load external data including XML.
Updated code with pastie.
I'm finding your code's structure a little odd - why do you have functions inside of a function?
I rewrote your code like this and it works perfectly fine (i just ran it on the timeline in flash cause i'm too lazy to set up a new project):
var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();
var request:URLRequest = new URLRequest("http://www.gessnerengineering.com/projects");
request.method = URLRequestMethod.GET;
//=============================================================================================
function openXML(name:String):void { //decides what XML data feed and opens it
//=============================================================================================
//add event listener to URLLoader to call closeXML upon completion
xmlLoader.addEventListener(Event.COMPLETE, closeXML);
xmlLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
xmlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
xmlLoader.load(new URLRequest("http://www.gessnerengineering.com/projects"));
}
function onIOError(e:IOErrorEvent):void {
trace("Error loading URL.");
}
function securityError(e:SecurityErrorEvent):void {
trace("security error");
}
function closeXML(e:Event):void {
trace('xmlLoader.data ' + xmlLoader.data);
xmlData = new XML(xmlLoader.data);
xmlLoader.removeEventListener(Event.COMPLETE, closeXML);
}
openXML('ljkl');
Without knowing all of the details, and assuming you implemented the RESTful services properly, your URLRequest might be calling the service with the wrong method (POST, rather than GET).
Check out this tutorial about calling RESTful services from Actionscript 3:
Consuming REST web Services in ActionScript 3
It has some good info on setting the request type and dealing with some of the other issues that can pop up (like setting the return data type, etc.).

Why is my URLLoader not dispatching when it completes?

I'm using a URLLoader to send a few key/value pairs to a php script, which then turns them into an e-mail, sends it (or not), and then echoes a string with a response.
At first it works fine. The URLLoader posts, and I get my e-mail a minute later, but for some reason I'm not getting my response back. In fact, my COMPLETE event doesn't seem to fire at all. This is confusing me because if I'm getting my e-mail, I know I must be sending everything properly. Here's my code:
public class Mailman{
public static const METHOD:String = URLRequestMethod.POST;
public static const ACTION:String = "mailer.php";
public static var myLoader:URLLoader = new URLLoader();
private static function onMessageProgress(e:Event){
var L:URLLoader = e.target as URLLoader;
Output.trace("PROGRESS: "+L.bytesLoaded+"/"+L.bytesTotal);
for(var k in L){
Output.trace(" "+k+": "+L[k]);
}
}
private static function onOpen(e:Event){
Output.trace("Connection opened");
}
private static function onComplete(e:Event){
Output.trace("Complete!");
}
private static function onStatusChange(e:HTTPStatusEvent){
Output.trace("Status Changed to "+e.status);
}
private static function onMessageFail(e:Event){
PanelManager.alert("ERROR: Could not send your request. Please try again later.");
}
public static function sendMessage(recipient:String,subject:String,message:String){
var _vars:URLVariables = new URLVariables();
_vars.recipient = recipient;
_vars.subject = subject;
_vars.message = message;
var req:URLRequest = new URLRequest(ACTION);
req.data = _vars;
req.method = METHOD;
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
myLoader.addEventListener(ProgressEvent.PROGRESS,onMessageProgress);
myLoader.addEventListener(Event.OPEN,onOpen);
myLoader.addEventListener(Event.COMPLETE,onComplete);
myLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS,onStatusChange);
myLoader.addEventListener(IOErrorEvent.IO_ERROR,onMessageFail);
myLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onMessageFail);
myLoader.load(req);
}
public static function test(){
sendMessage("john#example.com","test","this is a test message.");
}
function Mailman(){}
}
When I call Mailman.test(), I get my e-mail exactly like I expect, and this is what traces out:
Connection opened
PROGRESS: 45/45
Status Changed to 0
How can this be? If I'm understanding the documentation properly, the Open event happens when I begin downloading my response, and clearly that is happening, so how can I get back an http status of 0? Any ideas?
I found it.
The problem was with the URLLoader's dataFormat. This is the format for what you're getting BACK, not what you're sending. I switched it to URLLoaderDataFormat.TEXT and it worked perfectly.
Another reason this could happen - if you use weak references when registering your event listeners, and do not keep a reference to your URLLoader instance and the instance handling the event(s), GC may clean them up before they can receive any events.
//make sure the URLLoader and onComplete instances are not local vars
var req:URLRequest = new URLRequest("dosomething.php");
myLoader.addEventListener(Event.COMPLETE, onComplete, false, 0, TRUE);
myLoader.load(req);
Ok I found the answer in my case it was .NET page which was responsible for Status=0 in Chrome. What we were doing that in .net page at the line after writing response to be sent back to flash, we were closing the response object which was reseting the page and because of which Chrome was showing status=0 and couldn't render the result. After commenting out the response.close line it started working fine.
I wrote my experience with this problem and how i was able to solve it at http://viveklakhanpal.wordpress.com/2010/07/01/error-2032ioerror/
Thanks,
Vivek.