views:

562

answers:

2

Hi all,

I was trying to retrieve binary data over HTTP for my Flex application, and was running into some stumbling blocks. HTTPService did not seem to deal with binary data well, people said to use URLLoader. But URLLoader does not have the nice AsyncToken/IResponder interface that HTTPService provides.

So, I did some searching and could not find anyone extending URLLoader to provide this kind of functionality. I went ahead and took a stab at it myself: http://pastebin.com/d7369d0e0

Basically it wraps a URLLoader and an AsyncToken, and maps the COMPLETE, IO_ERROR, and SECURITY_ERROR events from URLLoader to results/faults that get raised on the AsyncToken.

Basic usage:

var tidbitLoader:AsyncURLLoader = new AsyncURLLoader();
tidbitLoader.dataFormat = URLLoaderDataFormat.BINARY;

var asyncToken:AsyncToken = tidbitLoader.load(new URLRequest("http://localhost/SampleTidbit.swf"));

asyncToken.addResponder(this);

public function result(resultEvent:Object):void
{
    trace("result");
}

public function fault(faultEvent:Object):void 
{
    var fault:FaultEvent = faultEvent as FaultEvent;
    trace("fault: " + fault.toString());
}

Is this the right way to approach the problem? Are there existing solutions? I would love to hear feedback.

Thanks,

Karthik

+1  A: 

Use the resultFormat = text on the HTTPService and then create a new ByteArray and call writeUTFBytes to write the text from the HTTPService result to the ByteArray. Then you should be able to set that ByteArray to a SWFLoader.source or call Loader.loadBytes.

James Ward
A: 

I have tried your solution James with an AIR 1.5 app, but I get the following error when I set the ByteArray on my SWFLoader.source. Any ideas? I thought I read somewhere that AIR changes the HTTP headers and this may be the cause? Thanks Ben.

[DEBUG] mx.messaging.Channel 'direct_http_channel' channel sending message: (mx.messaging.messages::HTTPRequestMessage)#0 body = (Object)#1 clientId = (null) contentType = "application/x-www-form-urlencoded" destination = "DefaultHTTP" headers = (Object)#2 httpHeaders = (Object)#3 messageId = "3044E76C-CF0E-2D5F-96BE-74CFF62098B0" method = "GET" recordHeaders = false timestamp = 0 timeToLive = 0 url = "http://www.myurl.com/test.jpg" [INFO] mx.messaging.Producer '4FA2CCF4-2B3E-4EAB-2873-74CFF612AA72' producer connected. [INFO] mx.messaging.Producer '4FA2CCF4-2B3E-4EAB-2873-74CFF612AA72' producer acknowledge of '3044E76C-CF0E-2D5F-96BE-74CFF62098B0'. [INFO] mx.rpc.http.HTTPService Decoding HTTPService response [DEBUG] mx.rpc.http.HTTPService Processing HTTPService response message: (mx.messaging.messages::AcknowledgeMessage)#0 body = "ÿØÿà Error #2044: Unhandled IOErrorEvent:. text=Error #2124: Loaded file is an unknown type.

Ben Marinic