AS3: HTTP Authentication with URLLoader, Sound (loader), Loader
I recently needed to load data from a private feed into both a JSON object (for deserialization) and multiple sound files in MP3 format. The way to do this is rather straight forward, but there were a couple gotchas I encountered along the way. Here they are in no particular order:
- - Loader objects (URLLoader, Loader, Sound) will not pass any authentication information in their headers unless the request uses the POST verb.
- - A Loader object (or more precisely, a URLRequest object) will not actually use the POST method unless there is some type of data in the URLRequest’s “data” property.
Essentially, if you want to do a simple GET with HTTP Authentication, you can’t. You not only need to do a POST, you also have to send it POST data, even if it doesn’t require it.
Here is an example of setting up HTTP Authentication using the POST method and sending in fake data:
var _queryLoader:URLLoader = new URLLoader();
var _queryRequest:URLRequest = new URLRequest();
_queryRequest.url = "http://yoururlhere.com/";
// POST is required for HTTP Auth headers to be passed
_queryRequest.method = "POST";
// Some type of POST data must be present for POST to happen in the first place
_queryRequest.data = "dummy_data=needed_for_post_to_work";
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode(Username + ":" + Password)
var authString = "Basic " + encoder.toString();
var _queryAuthorizationHeader:URLRequestHeader = new URLRequestHeader("Authorization", authString);
_queryRequest.requestHeaders.push(_queryAuthorizationHeader);
var _queryTypeHeader = new URLRequestHeader("Content-Type", "application/x-www-form-urlencoded");
_queryRequest.requestHeaders.push(_queryTypeHeader);
_queryLoader.load(_queryRequest);
If you need to pass GET parameters anyways, you could probably pass them in the URL as a query string. I haven’t checked that yet, though.