unable to get HTTP response code/headers in actionscript 3? - actionscript-3

I'm using URLLoader to POST to a server. The xml response from the server can respond with a 404 or a 403 (forbidden) error. However I am unable to get the response codes.
Here is the code
var urlString:String = "some url";
var urlRequest:URLRequest = new URLRequest(urlString);
var loader:URLLoader = new URLLoader();
loader.addEventListener( Event.COMPLETE, setXMLData );
loader.addEventListener( IOErrorEvent.IO_ERROR, ioHandler );
loader.addEventListener( HTTPStatusEvent.HTTP_STATUS, httpStatusHandler );
//...
public function httpStatusHandler(evt:HTTPStatusEvent):void {
trace("status is " + evt.status);
}
status is always 0 regardless whether i return 200, 400, 404, 301, 500, etc...
Any ideas?

For AIR Only you can use the httpResponseStatus. Otherwise in Flash/Flex without AIR you cannot.
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/URLLoader.html#event:httpResponseStatus
httpResponseStatus Event
Event Object Type: flash.events.HTTPStatusEvent
HTTPStatusEvent.type property = flash.events.HTTPStatusEvent.HTTP_RESPONSE_STATUS
Language Version : ActionScript 3.0
Runtime Versions : AIR 1.0 AIR 1.0
Dispatched if a call to the load() method attempts to access data over HTTP, and Adobe AIR is able to detect and return the status code for the request.
Unlike the httpStatus event, the httpResponseStatus event is delivered before any response data. Also, the httpResponseStatus event includes values for the responseHeaders and responseURL properties (which are undefined for an httpStatus event. Note that the httpResponseStatus event (if any) will be sent before (and in addition to) any complete or error event.

the ability to look at the headers is limited in several browsers, therefore flash has a problem with being passed the information. this is mainly blamed on the browser settings, but i have yet to find one where it actually works. status event output.
i gave up and had the file print the response code in my projects, not wonderful (and somewhat defeating the point) but seems to work.

As a late answer (FWIW):
From what I've read, the status codes you get depend on what browser the Flash player is running in.
One article says you can only get 200 or 500. One SO question says they were getting 207 in Chrome but 0 in Firefox.
I, personally, have tested using the dev Flash player as well as an ActiveX version and was able to get many different 2XX/4XX HTTP status codes (but couldn't get the 3XX redirect codes I tried because the requests got redirected and returned 200s).

Related

Flash AS3 read proxy server response with URLLoader

I am running an embedded flash 'swf' inside a LAN network with a proxy server. Proxy server interrupts some urls and returns my usage information. I am trying to access this information by sending those urls. I can see this traffic in firebug ,But the URLLoader does not seem to read it. Neither Complete event or progress event get fired. I tried URLStream with a timer also,but availableBytes were always zero.Is it possible to read this information?
private var getLoader:URLLoader = new URLLoader();
private var sendRequest:URLRequest = new URLRequest();
public function XDomain() {
sendRequest= new URLRequest("requesturl");
getLoader.addEventListener(Event.COMPLETE, eventHandler);
getLoader.addEventListener(ProgressEvent.PROGRESS,eventHandler2);
getLoader.load(sendRequest);
}
private function eventHandler(event:Event):void {
trace("running");
}
private function eventHandler2(event:ProgressEvent):void {
trace("runninhg progresss");
}
Thanks in advance //
Edit: I had this security error
[SecurityErrorEvent type="securityError" bubbles=false cancelable=false eventPhase=2 text="Error #2048"]
"But the URLLoader does not seem to read it..."
Use URLStream (without a timer, cos what does that even achieve?) to reach the link and inside your related progressEvent use a readUTFBytes to get any text response data given by that link's server. Use progressEvent to also check size of any received bytes (the event fires multiple times, getting 64kb packets, until full data is downloaded).
about Error #2048:
URLloader is a decoder for visual data (jpg, png, swf, text) but for non-text data it expects a crossdomain.xml to exist at the other server you are accessing the swf from (both sides must also have a matching same http or https. Again best way to by-pass this is to just load the bytes into a byte array (via URLStream but the progressEvents now should write to your byte array) then later use URLLoader.loadBytes( yourSWFBytes );

As3 When i use Loader,i always get httpstatus code 200 event though the httpstatus code in google chrome is 304

In As3, I use
_loader.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHttpStatus);
to detect the httpstatus code of Loader. In the callback function the httpstatus code is 200 when the httpstatus code show in google chrome is exactly 304.
In reality, that should be the same thing because these status are reponses to your request sent by the web server, but with Flash while the requested file is in the cache, you will get always 200 HTTP status because in this case the lazy Flash didn't even sends a request to the web server and give you a fake 200 HTTP status. With Air, the situation is a little bit different because It gives you 200 HTTP status for a real 200 and for 304 HTTP status ( Not Modified ) despite Air do a real request every time.
To verify all that we can use this simple ActionScript code :
var loader:URLLoader = new URLLoader();
loader.addEventListener(
HTTPStatusEvent.HTTP_STATUS,
function(e:HTTPStatusEvent):void {
trace('http status : ' + e.status)
}
)
loader.load(new URLRequest('http://www.example.com'));
Flash will give you always the 200 HTTP status for a reachable content of course. You can try with an on line URL and then disconnect your machine from Internet, you will get always the same value : 200.
For Air, the first request it's a real 200, but the second, if the file is cachebal, you will get 200 but in reality Air receive 304 response. To verify that, you can use a local web server and you will find web server responses in it's logs as 200 for the first request and 304 for the second one, or you can use a capturing network traffic tool as Fiddler and you will see directly responses received in reality by your Air app.
I hope that's more clear now for you.
Use a random number to generate "new" links and avoid the cache effect
var loader:URLLoader = new URLLoader();
var noCache:Number = Math.random()
loader.addEventListener(
HTTPStatusEvent.HTTP_STATUS,
function(e:HTTPStatusEvent):void {
trace('http status : ' + e.status)
}
)
loader.load(new URLRequest('http://www.example.com?c='+noCache));

Flex mobile HTTPMultiService set user-agent

I'm developing a Flex mobile application and I'm using the Http Services within FlashBuilder (4.7) to send/receive data. I'm having some issues with how the server is setup to accept calls (from the mobile platform) and apparently setting the User-Agent in Android works just fine. But I can't seem to be able to find a way to set the User-Agent in FlashBuilder.
Any ideas?
Thanks
var request:URLRequest=new URLRequest('URL_OF_YOUR_SERVICE');
var userCredential:Object = new Object();
userCredential['user_email'] = 'YOUR_MAIL';
userCredential['user_password'] = 'YOUR_PASSWORD';
request.data=JSON.stringify(userCredential);// use this if your service accept json only else give Object directly
request.method = 'post';// specify here method GET or POST
var loader:URLLoader=new URLLoader();
loader.addEventListener(Event.COMPLETE, userLoginCompleteHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, onIOErrorHanlder);
try
{
loader.load(request);
}
catch(error:Error)
{
trace("Login Error:: "+ error.toString());
}
may this will help you, here i have defined userLoginCompleteHandler and onIOErrorHanlder event listner for result and fault.
No, you can't set the User-Agent header in Flex.
From this Adobe forums post:
Note again that since the underlying Flash API is flash.net.URLLoader there are certain headers that
you cannot send. For details, please see the docs for flash.net.URLRequestHeader.
The URLRequestHeader docs say:
In Flash Player and in Adobe AIR content outside of the application
security sandbox, the following request headers cannot be used:
... User-Agent, ...

POST file upload using URLRequest

I have a quick question regarding POST file uploads in ActionScript 3. I am trying to upload a ByteArray from memory via POST to a server. I'm using the URLRequest class to send the data, and URLLoader because I want to monitor the progress. The relevant sections of code follows:
var uploadRequest:URLRequest = new URLRequest("http://127.0.0.1/upload.php");
uploadRequest.method = URLRequestMethod.POST;
uploadRequest.contentType = "multipart/form-data";
uploadRequest.data = myByteArray;
var uploader:URLLoader = new URLLoader;
uploader.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
uploader.addEventListener(Event.COMPLETE, onUploadComplete);
uploader.dataFormat = URLLoaderDataFormat.BINARY;
uploader.load(uploadRequest);
The problem is that I've set my callbacks to trace the upload progress, and the bytesTotal property of the ProgressEvent is always 1960 (the size of the request minus data?), even though the actual data is around 20MB and no file is uploaded even after the Complete event fires.
I've verified that upload.php functions correctly with a simple html form, and I can verify that myByteArray contains all of the data in question. Can anyone tell me what I'm doing wrong?
Edit:
I've attempted a couple of new things that I thought I should mention. The first is setting the content type to application/octet-stream instead of multipart/form-data, which had no effect other than increasing the number of bytes to 1964. I also checked the Apache error log and found the following text repeated a lot:
PHP Warning: Missing boundary in multipart/form-data POST data in Unknown on line 0
I'm guessing that Flash isn't formatting the HTTP request properly for whatever reason. Given that I created a FileReference that makes use of the same methods I set for the URLLoader to upload a file from disk, and got the expected result: the bytesTotal property matched the file size and the file was uploaded correctly.
Working from that I found a page in the Adobe developer docs that mentions uploading data to a server using FileReference.upload() by setting the data parameter of the URLRequest, so I tried the following code:
var uploadRequest:URLRequest = new URLRequest("http://127.0.0.1/upload.php");
uploadRequest.method = URLRequestMethod.POST;
uploadRequest.data = myByteArray;
fileRef = new FileReference;
fileRef.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
fileRef.addEventListener(Event.COMPLETE, onUploadComplete);
fileRef.upload(uploadRequest);
Which resulted in the following output:
ArgumentError: Error #2127: FileReference POST data cannot be type ByteArray.
I'm really stuck here. Any suggestions would be appreciated!
You should add more info to the "Content-Type" header:
uploadRequest.contentType = "multipart/form-data; boundary=<<boundary here>>";

AS3-ID3 event in a web radio

I'm building an online radio player using the AS3 code below:
private var soundChannel:SoundChannel;
private var stationUrl:String = "h t t p : / /205.188.215.230:8002/";
sound = new Sound();
sound.addEventListener(Event.ID3, onID3Change);
sound.load(new URLRequest(stationUrl));
soundChannel = sound.play();
private function onID3Change(e:Event):void
{
....
}
the sound plays successfully, but the problem is that the ID3 event is never triggered!
Does anyone know how to solve this?
ID3 doesn't exist in internet radio streams like this one. I am assuming you're talking about a SHOUTcast/IceCast stream.
For that, you need to implement the icy metadata protocol. For Flash, this is generally just done externally.
See this reference: http://www.smackfu.com/stuff/programming/shoutcast.html
Basically, you send icy-metadata: 1 in the headers of your GET request. The server then inserts metadata right into the middle of the stream, which you pull out before sending the data on to whatever is playing the stream. I'm not sure if this is even possible in Flash, but it certainly is possible to do this in PHP (or any server-side language really) and have your Flash application make a request to your PHP script to get that metadata.