Air, Android, and cookies

What: In using an Android app, I need to send an authentication request (username/password) to the server and the server needs to send me back a cookie.  We all know how you would use JavaScript to grab cookie/session data and then you could send it right into flash.

Problem: How or where would you find cookie being sent to you in your Air/Android app that uses no browser?

Solution:  Headers can be found in the HTTPStatusEvent object!  Hurray!  It took me way too long to find the answer to this issue.  Everyone on google is happy to tell you “Hey there’s a manageCookies setting on the URLRequest object!”  Great, how do you find the damn headers?  In fact, as you’ll see in the following code, you dont even need to mess with that manageCookies setting.  I set it to true and got headers.  I set it to false and god headers.  I didn’t include it at all and got headers.  Sweet.

This is a sample piece of code, not a full working package.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public function testCall():void  {
	urlLoader = new URLLoader();
 
	urlRequest = new URLRequest();
	urlRequest.url = URL_PATH;
 
	var vars:URLVariables = new URLVariables();
	vars.user 	= "myUserName";
	vars.pass	= "myPassword";
 
	urlRequest.data = vars;
 
	urlLoader.addEventListener( IOErrorEvent.IO_ERROR , onErrorHandler );
	urlLoader.addEventListener( Event.COMPLETE , onLoaderCompleteHandler );
	urlLoader.addEventListener( HTTPStatusEvent.HTTP_RESPONSE_STATUS , onResponseStatus );
 
	urlLoader.load( urlRequest );
}
 
private function onErrorHandler( e:IOErrorEvent ):void  {
	trace( "IOErrorEvent: " + e.target.data.toString() );
}
 
private function onLoaderCompleteHandler( e:Event ):void  {
	trace( "Response Data: " + e.target.data.toString() );
}
 
private function onResponseStatus( e:HTTPStatusEvent ):void  {
	trace( "## HEADERS ##: " );
	for each( var i in e.responseHeaders )  {
		trace( "name: " + i.name + "nvalue: " + i.value + "n" ); 
	}
}

Line 15: We add an event listener for HTTPStatusEvent.HTTP_RESPONSE_STATUS and then we display those HTTPStatusEvent responseHeaders in the file starting at Line 28. Since you can get to those responseHeaders in the array, you can iterate through them until you find the piece of data that you need.

I took a screenshot of my debugger.  You can see where the requestHeaders are in relation to the HTTPStatusEvent object.

response headers in flashbuilder debugger
Response Headers

1 Comment

 Add your comment
  1. Hi Haelix,
    I’m using URLRequest to make HTTP connection and I use URLRequestHeader to set my cookie but it doesn’t work. Can you suggest me a way to set cookie in the request?

Leave a Comment

Your email address will not be published.