Flex http请求
下面类支持POST和GET请求,请求数据和出错将返回
package com.sole.util { import flash.events.Event; import flash.events.HTTPStatusEvent; import flash.events.IEventDispatcher; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLVariables; public class HttpConnent { /**请求的url*/ public var url:String; /**请求的参数*/ public var urlVariables:URLVariables; // public var resultStr:String; public var inputstream:Object; private var urlLoader:URLLoader; private var request:URLRequest; public var completeFun:Function; public var errFun:Function; /** *连接提交请求 * @method 请求类型 * post或get 默认post * @isstream 是否数据流请求 */ public function gotoConn(method:String=URLRequestMethod.POST,isstream:Boolean=false):void{ urlLoader = new URLLoader(); //URLLoader 类以文本、二进制数据或 URL 编码变量的形式从 URL 下载数据 request= new URLRequest(url); request.method = method;//设置请求的类型 if(isstream){ request.contentType= "application/octet-stream"; request.data=inputstream; urlLoader.dataFormat = URLLoaderDataFormat.BINARY; } if(urlVariables) request.data = urlVariables;//将url请求的数据放入request中 configureListeners(urlLoader);//给urlloader对象添加监听事件 try { urlLoader.load(request);//开始发送请求 } catch (error:Error) { trace(error); urlLoader.close(); } } private function configureListeners(dispatcher:IEventDispatcher):void { //加载完成事件; dispatcher.addEventListener(Event.COMPLETE, loaderHandler); //开始访问事件; dispatcher.addEventListener(Event.OPEN, loaderHandler); //加载进度事件; dispatcher.addEventListener(ProgressEvent.PROGRESS, loaderHandler); //跨域访问安全策略事件; dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loaderHandler); //Http状态事件; dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, loaderHandler); //访问出错事件; dispatcher.addEventListener(IOErrorEvent.IO_ERROR, loaderHandler); } private function loaderHandler(event:*):void { switch(event.type) { case Event.COMPLETE: trace("成功: "); if(completeFun!=null){ completeFun.call(null,event); } break; case Event.OPEN: trace("open: " + event); break; case ProgressEvent.PROGRESS: trace("progress: " + event); break; case SecurityErrorEvent.SECURITY_ERROR: trace("securityError: " + event); if(errFun!=null){ errFun.call(null); } break; case HTTPStatusEvent.HTTP_STATUS: trace("httpStatus: " + event); break; case IOErrorEvent.IO_ERROR: trace("ioError: " + event); if(errFun!=null){ errFun.call(null); } break; } } } }
调用该方法
var url:String=""; var variables:URLVariables = new URLVariables(); variables.ID = UserID; var http:HttpConnent=new HttpConnent(); http.url=url; http.urlVariables=variables; http.completeFun=customerNumberFun; http.errFun=customerNumberErrFun; http.gotoConn(URLRequestMethod.GET);