PageRenderTime 477ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/flash_crossxhr/HTTPURLLoader.as

http://crossxhr.googlecode.com/
ActionScript | 196 lines | 157 code | 24 blank | 15 comment | 22 complexity | da2ee050a65060c3e459882c68d41c01 MD5 | raw file
  1. /**
  2. HTTPURLLoader is small http client for GET requests and header manipulation.
  3. @class HTTPURLLoader (public)
  4. @author Abdul Qabiz (mail at abdulqabiz dot com)
  5. @version 1.01 (3/5/2007)
  6. @availability 9.0+
  7. Modified by Boris Reitman
  8. */
  9. package {
  10. import flash.net.*;
  11. import flash.events.*;
  12. import flash.system.Security;
  13. import flash.errors.EOFError;
  14. import flash.utils.*;
  15. import mx.utils.StringUtil;
  16. dynamic public class HTTPURLLoader extends EventDispatcher
  17. {
  18. [Event(name="close", type="flash.events.Event.CLOSE")]
  19. [Event(name="complete", type="flash.events.Event.COMPLETE")]
  20. [Event(name="open", type="flash.events.Event.CONNECT")]
  21. [Event(name="ioError", type="flash.events.IOErrorEvent.IO_ERROR")]
  22. [Event(name="securityError", type="flash.events.SecurityErrorEvent.SECURITY_ERROR")]
  23. [Event(name="progress", type="flash.events.ProgressEvent.PROGRESS")]
  24. [Event(name="httpStatus", type="flash.events.HTTPStatusEvent.HTTP_STATUS")]
  25. private var socket:Socket;
  26. private var headerComplete:Boolean = false;
  27. private var headerTmp:String = "";
  28. private var _httpPort:uint = 80;
  29. private var _request:URLRequest;
  30. public var _httpRequest:String;
  31. public var _httpServer:String;
  32. private var _header:Object;
  33. private var _data:String = "";
  34. private var _bytesLoaded:int = 0;
  35. private var _bytesTotal:int = 0;
  36. private var _httpVersion:Number;
  37. private var _httpStatusCode:int;
  38. private var _httpStatusText:String;
  39. public function HTTPURLLoader(request:URLRequest = null) {
  40. //doesn't really need it here, as load(..) requires request
  41. _request = request;
  42. socket = new Socket();
  43. socket.addEventListener( "connect" , onConnectEvent , false , 0 );
  44. socket.addEventListener( "close" , onCloseEvent , false, 0 );
  45. socket.addEventListener( "ioError" , onIOErrorEvent , false, 0 );
  46. socket.addEventListener( "securityError" , onSecurityErrorEvent , false, 0 );
  47. socket.addEventListener( "socketData" , onSocketDataEvent , false , 0 );
  48. }
  49. public function load(request:URLRequest):void {
  50. _request = request;
  51. if(parseURL())
  52. try { socket.connect(_httpServer, _httpPort); } catch (e:Error) { }
  53. else
  54. throw new Error("Invalid URL");
  55. }
  56. public function close():void {
  57. if(socket.connected) {
  58. socket.close();
  59. dispatchEvent(new Event(Event.CLOSE));
  60. }
  61. }
  62. public function get data():String {
  63. return _data;
  64. }
  65. public function get header():Object {
  66. return _header;
  67. }
  68. public function get bytesLoaded():int {
  69. return _bytesLoaded;
  70. }
  71. public function get bytesTotal ():int {
  72. return _bytesTotal;
  73. }
  74. private function onConnectEvent(event:Event):void {
  75. sendHeaders();
  76. dispatchEvent(new Event(Event.CONNECT));
  77. }
  78. private function onCloseEvent(event:Event):void {
  79. dispatchEvent(new Event(flash.events.Event.COMPLETE));
  80. }
  81. private function onIOErrorEvent(event:IOErrorEvent):void {
  82. dispatchEvent(event);
  83. }
  84. private function onSecurityErrorEvent(event:SecurityErrorEvent):void {
  85. dispatchEvent(event.clone());
  86. }
  87. private function onSocketDataEvent(event:ProgressEvent):void {
  88. _bytesLoaded += socket.bytesAvailable;
  89. dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, false, false, _bytesLoaded, _bytesTotal))
  90. var str:String = "";
  91. try { str = socket.readUTFBytes(socket.bytesAvailable); } catch(e:Error) { }
  92. if(!headerComplete) {
  93. var httpStatus:String;
  94. var headerEndIndex:int = str.indexOf("\r\n\r\n");
  95. if(headerEndIndex != -1) {
  96. headerTmp += str.substring(0, headerEndIndex);
  97. headerComplete = true;
  98. _data += str.substring(headerEndIndex + 4);
  99. var headerArr:Array = headerTmp.split("\r\n");
  100. var headerLine:String;
  101. var headerParts:Array;
  102. for each(headerLine in headerArr) {
  103. if(headerLine.indexOf("HTTP/1.") != -1) {
  104. headerParts = headerLine.split(" ");
  105. if(headerParts.length > 0)
  106. _httpVersion = parseFloat(StringUtil.trim(headerParts.shift().split("/")[1]));
  107. if(headerParts.length > 0)
  108. _httpStatusCode = parseInt(StringUtil.trim(headerParts.shift()));
  109. if(headerParts.length > 0)
  110. _httpStatusText = StringUtil.trim(headerParts.join(" "));
  111. dispatchEvent(new HTTPStatusEvent(HTTPStatusEvent.HTTP_STATUS, false, false, _httpStatusCode));
  112. } else {
  113. var colonIndex:int = headerLine.indexOf(":");
  114. if(colonIndex != -1) {
  115. var key:String = StringUtil.trim(headerLine.substring(0, colonIndex));
  116. var value:String = StringUtil.trim(headerLine.substring(colonIndex + 1));
  117. if (!_header)
  118. _header = new Object ();
  119. _header[key] = value;
  120. }
  121. }
  122. }
  123. if(_header["Content-Length"])
  124. // total bytes = content-length + header size (number of characters in header)
  125. // not working, need to work on right logic..
  126. _bytesTotal = int(_header["Content-Length"]) + headerTmp.length;
  127. } else
  128. headerTmp += str;
  129. } else
  130. _data += str;
  131. }
  132. private function sendHeaders():void
  133. {
  134. var requestHeaders:Array = _request.requestHeaders;
  135. var h:String = "";
  136. _header = null;
  137. _bytesLoaded = 0;
  138. _bytesTotal = 0;
  139. _data = "";
  140. headerComplete = false;
  141. headerTmp = "";
  142. //create an HTTP 1.0 Header Request
  143. h+= "GET " + _httpRequest + " HTTP/1.0\r\n";
  144. h+= "Host:" + _httpServer + "\r\n";
  145. if(requestHeaders.length > 0) {
  146. for each(var rh:URLRequestHeader in requestHeaders)
  147. h+= rh.name + ":" + rh.value + "\r\n";
  148. }
  149. //set HTTP headers to socket buffer
  150. socket.writeUTFBytes(h + "\r\n\r\n")
  151. //push the data to server
  152. socket.flush()
  153. }
  154. private function parseURL():Boolean {
  155. var d:Array = _request.url.split('http://')[1].split('/');
  156. if(d.length > 0)
  157. {
  158. _httpServer = d.shift();
  159. var d2:Array = _httpServer.split(':');
  160. if (d2.length>0) {
  161. _httpServer = d2[0];
  162. _httpPort = d2[1];
  163. }
  164. Security.loadPolicyFile("http://"+_httpServer+':'+_httpPort+"/crossdomain.xml");
  165. _httpRequest = '/' + d.join('/');
  166. return true;
  167. }
  168. return false;
  169. }
  170. }
  171. }