---
title: "[转]Flex与ASP.NET互操作系列4：使用HttpService、URLReqeust和URLLoader加载/传输数据"
author: "ilinker"
date: "2010-01-07T11:45:38Z"
tags: []
categories: ["Web前端"]
slug: "flex-asp-net-4-httpservice-urlreqeust-urlloader"
draft: false
lastmod: "2010-01-07T11:45:38Z"
id: 564606
url: "https://ilinker.iteye.com/blog/564606"
---

在前两篇文章中分别介绍了Flex与.NET的WebService之间的数据交互通信知识，本文将介绍另外一种加载数据以及发起请求的方式。ActionScript 3.0中提供的数据加载请求类主要是HTTPService,URLLoader和URLRequest，可以通过他们协同来完成数据加载和请求。下面我么便来看看这三个类是怎么来完成数据加载工作。  
     在本地IIS服务器上有如下定义的XML文件：

 1 &lt;?xml version="1.0" encoding="utf-8" ?&gt;  
 2 &lt;Root&gt;  
 3   &lt;Book&gt;  
 4     &lt;Id&gt;1&lt;/Id&gt;  
 5     &lt;Name&gt;《三国演义》&lt;/Name&gt;  
 6     &lt;Author&gt;罗贯中&lt;/Author&gt;  
 7     &lt;Price&gt;52.30&lt;/Price&gt;  
 8   &lt;/Book&gt;  
 9   &lt;Book&gt;  
10     &lt;Id&gt;2&lt;/Id&gt;  
11     &lt;Name&gt;《西游记》&lt;/Name&gt;  
12     &lt;Author&gt;吴承恩&lt;/Author&gt;  
13     &lt;Price&gt;39.91&lt;/Price&gt;  
14   &lt;/Book&gt;  
15   &lt;Book&gt;  
16     &lt;Id&gt;3&lt;/Id&gt;  
17     &lt;Name&gt;《红楼梦》&lt;/Name&gt;  
18     &lt;Author&gt;曹雪芹&lt;/Author&gt;  
19     &lt;Price&gt;48.20&lt;/Price&gt;  
20   &lt;/Book&gt;  
21   &lt;Book&gt;  
22     &lt;Id&gt;4&lt;/Id&gt;  
23     &lt;Name&gt;《水浒传》&lt;/Name&gt;  
24     &lt;Author&gt;施耐庵&lt;/Author&gt;  
25     &lt;Price&gt;39.85&lt;/Price&gt;  
26   &lt;/Book&gt;  
27 &lt;/Root&gt;

一、使用HTTPService传递和加载数据

     使用HTTPService可以实现加载数据，也可以实现参数传递，下面通过两个示例程序来讲解这两个知识点。

     首先来看看HTTPService加载数据的方式。在Flex中使用HTTPService来装载外部数据是非常简单的，他是基于HTTP协议发送POST和GET请求外部数据,然后通过指定的监听方法来处理响应。我们可以通过&lt;mx:HTTPService&gt;标签来完成对数据源的连接，也可以通过可编程方式来处理,两种方式没什么大的差距，实际开发中可以根据自己喜好选择。

 1 internal function onClick():void  
 2 {  
 3     var service:HTTPService = new HTTPService();  
 4     service.url = "[http://localhost:1146/Data/Book.xml](http://localhost:1146/Data/Book.xml)";  
 5     service.useProxy = false;  
 6     service.resultFormat="e4x";  
 7     service.addEventListener(ResultEvent.RESULT,onResultHandler);  
 8     service.send();  
 9 }  
10  
11 internal function onResultHandler(evt:ResultEvent):void  
12 {  
13     var xml:XML = evt.result as XML;  
14     trace(xml);  
15     bookGrid.dataProvider = xml.Book;  
16 }  
 

     该示例的运行结果见文章最后，下面是这个示例的完整代码：

完整示例代码  
 1 &lt;?xml version="1.0" encoding="utf-8"?&gt;  
 2 &lt;mx:Application xmlns:mx="[http://www.adobe.com/2006/mxml](http://www.adobe.com/2006/mxml)" layout="absolute"&gt;  
 3     &lt;mx:Script&gt;  
 4         &lt;![CDATA[  
 5             import mx.rpc.events.FaultEvent;  
 6             import mx.rpc.events.ResultEvent;  
 7             import mx.rpc.http.HTTPService;  
 8              
 9             internal function onClick():void  
10             {  
11                 var service:HTTPService = new HTTPService();  
12                 service.url = "[http://localhost:1146/Data/Book.xml](http://localhost:1146/Data/Book.xml)";  
13                 service.useProxy = false;  
14                 service.resultFormat="e4x";  
15                 service.addEventListener(ResultEvent.RESULT,onResultHandler);  
16                 service.send();  
17             }  
18              
19             internal function onResultHandler(evt:ResultEvent):void  
20             {  
21                 var xml:XML = evt.result as XML;  
22                 trace(xml);  
23                 bookGrid.dataProvider = xml.Book;  
24             }  
25         ]]&gt;  
26     &lt;/mx:Script&gt;  
27  
28     &lt;mx:Panel x="49.5" y="94" width="419" height="267" layout="absolute" fontSize="12" title="使用HTTPService加载XML数据"&gt;  
29         &lt;mx:DataGrid x="10" y="10" width="377" id="bookGrid"&gt;  
30             &lt;mx:columns&gt;  
31                 &lt;mx:DataGridColumn headerText="编号" dataField="Id"/&gt;  
32                 &lt;mx:DataGridColumn headerText="书名" dataField="Name"/&gt;  
33                 &lt;mx:DataGridColumn headerText="作者" dataField="Author"/&gt;  
34                 &lt;mx:DataGridColumn headerText="价格" dataField="Price"/&gt;  
35             &lt;/mx:columns&gt;  
36         &lt;/mx:DataGrid&gt;  
37         &lt;mx:ControlBar height="42"&gt;  
38             &lt;mx:Button label="加载数据" fontWeight="normal" click="onClick()"/&gt;  
39         &lt;/mx:ControlBar&gt;  
40     &lt;/mx:Panel&gt;  
41 &lt;/mx:Application&gt;  
42  
 

     OK，我们来看看使用HTTPService传递参数到服务端是怎么实现的。使用HTTPService传递参数可以通过两种方式实现，分别如下：

     1、直接在请求URL后面跟上参数列表，如：[http://localhost/web/Test.aspx?a=1&b=2](http://localhost/web/Test.aspx?a=1&b=2)。

     2、通过Flex SDK为我们提供专门用语参数传递的对象（URLVariables）来实现。

     下面以一道简单的加法运算来演示HTTPService传递参数的使用，在Flex里将需要进行加法运算的两个数传递到.NET服务端并计算其和后返回给Flex客户端，两种方式传递没有太大的区别，详细请看如下代码演示：

 1 /\**  
 2  * 通过RUL参数直接传递  
 3  * \*/  
 4 internal function onClick():void  
 5 {  
 6     var service:HTTPService = new HTTPService();  
 7     var a:String = txtA.text;  
 8     var b:String = txtB.text;  
 9     service.url = "[http://localhost:1146/OperationHandler.ashx?a="+a+"&b="+b](http://localhost:1146/OperationHandler.ashx?a=%22%20a%20%22&b=%22%20b);  
10     service.useProxy = false;  
11     service.resultFormat="e4x";  
12     service.addEventListener(ResultEvent.RESULT,onResultHandler);  
13     service.send();  
14 }  
15  
16 /\**  
17  * 通过URLVariables进行参数传递  
18  * \*/  
19 internal function onClick():void  
20 {  
21     var service:HTTPService = new HTTPService();  
22     service.url = "[http://localhost:1146/OperationHandler.ashx](http://localhost:1146/OperationHandler.ashx)";  
23     service.useProxy = false;  
24     service.resultFormat="e4x";  
25     service.addEventListener(ResultEvent.RESULT,onResultHandler);  
26     var param:URLVariables = new URLVariables();  
27     param.a = txtA.text;  
28     param.b = txtB.text;  
29     service.send();  
30 }  
 

      下面是完整的示例代码，可以把onClick()方法相互切换来测试两种不同的参数传递方式。

完整的示例代码  
 1 &lt;?xml version="1.0" encoding="utf-8"?&gt;  
 2 &lt;mx:Application xmlns:mx="[http://www.adobe.com/2006/mxml](http://www.adobe.com/2006/mxml)" layout="absolute"&gt;  
 3     &lt;mx:Script&gt;  
 4         &lt;![CDATA[  
 5             import mx.rpc.events.FaultEvent;  
 6             import mx.rpc.events.ResultEvent;  
 7             import mx.rpc.http.HTTPService;  
 8              
 9             /\**  
10              * 通过RUL参数直接传递  
11              * \*/  
12             internal function onClick():void  
13             {  
14                 var service:HTTPService = new HTTPService();  
15                 var a:String = txtA.text;  
16                 var b:String = txtB.text;  
17                 service.url = "[http://localhost:1146/OperationHandler.ashx?a="+a+"&b="+b](http://localhost:1146/OperationHandler.ashx?a=%22%20a%20%22&b=%22%20b);  
18                 service.useProxy = false;  
19                 service.resultFormat="e4x";  
20                 service.addEventListener(ResultEvent.RESULT,onResultHandler);  
21                 service.send();  
22             }  
23              
24             /\**  
25              * 通过URLVariables进行参数传递  
26              * \*/  
27 //            internal function onClick():void  
28 //            {  
29 //                var service:HTTPService = new HTTPService();  
30 //                service.url = "[http://localhost:1146/OperationHandler.ashx](http://localhost:1146/OperationHandler.ashx)";  
31 //                service.useProxy = false;  
32 //                service.resultFormat="e4x";  
33 //                service.addEventListener(ResultEvent.RESULT,onResultHandler);  
34 //                var param:URLVariables = new URLVariables();  
35 //                param.a = txtA.text;  
36 //                param.b = txtB.text;  
37 //                service.send();  
38 //            }  
39              
40             internal function onResultHandler(evt:ResultEvent):void  
41             {  
42                 ab.text = evt.result.toString();  
43             }  
44         ]]&gt;  
45     &lt;/mx:Script&gt;  
46  
47     &lt;mx:Panel x="49.5" y="94" width="419" height="126" layout="absolute" fontSize="12" title="使用HTTPService传递参数"&gt;  
48         &lt;mx:TextInput x="33" y="10" width="91" id="txtA"/&gt;  
49         &lt;mx:Label x="10" y="12" text="A："/&gt;  
50         &lt;mx:Label x="132" y="12" text="B："/&gt;  
51         &lt;mx:TextInput x="165" y="10" id="txtB" width="79"/&gt;  
52         &lt;mx:Label x="252" y="12" text="A+B："/&gt;  
53         &lt;mx:TextInput x="293" y="10" width="95" id="ab"/&gt;  
54         &lt;mx:ControlBar height="44"&gt;  
55             &lt;mx:Button label="计 算" fontWeight="normal" click="onClick()"/&gt;  
56         &lt;/mx:ControlBar&gt;  
57     &lt;/mx:Panel&gt;  
58 &lt;/mx:Application&gt;  
59  
 

OperationHandler.ashx  
 1 public class OperationHandler : IHttpHandler  
 2 {  
 3  
 4     public void ProcessRequest(HttpContext context)  
 5     {  
 6         context.Response.ContentType = "text/plain";  
 7  
 8         int a = int.Parse(context.Request.QueryString\["a"]);  
 9         int b = int.Parse(context.Request.QueryString\["b"]);  
10  
11         context.Response.Write((a + b).ToString());  
12     }  
13  
14     public bool IsReusable  
15     {  
16         get  
17         {  
18             return false;  
19         }  
20     }  
21 }  
 

     上面示例的运行界面截图：

          ![](http://www.xueit.com/eimg/uploadfile/downpig/20092/09214231124442.jpg)

 

二、了解URLReqeust

     使用URLRequest 类可捕获单个 HTTP 请求中的所有信息。将URLRequest 对象传递给URLStream或URLLoader 类以及其他加载操作的load()方法以启动URL数据加载。它的使用很简单，通过构造方法构造对象就OK：

1 var request:URLRequest = new URLRequest("[http://localhost:1146/Data/Book.xml](http://localhost:1146/Data/Book.xml)")  
 

     同样可以使用URLRequest来请求一个本地项目/应用里的文件，如下代码示例：

1 var request:URLRequest = new URLRequest("Data/Book.xml")

     如上便构造好了URLRequest对象，只要将他传递给相应的对象load()方法便可实现数据加载。从某种角度可以将URLRequest理解为建立请求的工具。要是URLRequest类对象变成可用的对象还需得通过其他类来与之配合协作，详细见后面使用URLLoader加载数据。

     URLRequest虽然功能强大,使用简单。但我们还是需要了解更多的东西，以便可以正确的应用URLRequest类和处理相应的错误。其中最引人关注的就是安全沙箱的问题，这部分我将在以后的文章中介绍，这里只需要记住两点就OK。 

     1、如果执行调用的 SWF 文件在只能与本地文件系统内容交互的沙箱中，而目标资源来自网络沙箱，则不允许进行数据加载。

     2、如果执行调用的 SWF 文件来自网络沙箱而目标资源在本地，也不允许进行数据加载。

     这里就简单介绍这些，关于URLRequest的详细资料大家可以查看官方提供的在线文档：[http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/URLRequest.html](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/URLRequest.html)

 

三、使用URLLoader加载数据

     URLLoader 类可以以文本、二进制数据或 URL 编码变量的形式从 URL 下载数据。下面将结合使用本地服务器上的数据(详细见文章前面的xml文件定义)的加载示例来演示URLLoader的使用方法。

      那我们怎么通过URLLoader来加载它呢？很简单，使用上面介绍的URLRequest来创建请求连接，然后将URLRequest对象传递给URLLoader的load方法来实现数据加载。

 1 internal function onClick():void  
 2 {  
 3     var request:URLRequest = new URLRequest("[http://localhost:1146/Data/Book.xml](http://localhost:1146/Data/Book.xml)");  
 4     var loader:URLLoader = new URLLoader();  
 5     loader.load(request);  
 6     loader.addEventListener(Event.COMPLETE,onCompleteHandler);  
 7 }  
 8  
 9 private function onCompleteHandler(evt:Event):void  
10 {  
11     var xml:XML = new XML(evt.target.data);  
12     bookGrid.dataProvider = xml.Book;  
13 }  
     下面是整个mxml的代码定义：

mxml完整代码  
 1 &lt;?xml version="1.0" encoding="utf-8"?&gt;  
 2 &lt;mx:Application xmlns:mx="[http://www.adobe.com/2006/mxml](http://www.adobe.com/2006/mxml)" layout="absolute"&gt;  
 3     &lt;mx:Script&gt;  
 4         &lt;![CDATA[  
 5             internal function onClick():void  
 6             {  
 7                 var request:URLRequest = new URLRequest("[http://localhost:1146/Data/Book.xml](http://localhost:1146/Data/Book.xml)");  
 8                 var loader:URLLoader = new URLLoader();  
 9                 loader.load(request);  
10                 loader.addEventListener(Event.COMPLETE,onCompleteHandler);  
11             }  
12              
13             private function onCompleteHandler(evt:Event):void  
14             {  
15                 var xml:XML = new XML(evt.target.data);  
16                 bookGrid.dataProvider = xml.Book;  
17             }  
18         ]]&gt;  
19     &lt;/mx:Script&gt;  
20     &lt;mx:Panel x="49.5" y="94" width="419" height="267" layout="absolute" fontSize="12" borderColor="#E2E2E2" themeColor="#009DDF" title="使用URLLoader加在XML数据"&gt;  
21         &lt;mx:DataGrid x="10" y="10" width="377" id="bookGrid"&gt;  
22             &lt;mx:columns&gt;  
23                 &lt;mx:DataGridColumn headerText="编号" dataField="Id"/&gt;  
24                 &lt;mx:DataGridColumn headerText="书名" dataField="Name"/&gt;  
25                 &lt;mx:DataGridColumn headerText="作者" dataField="Author"/&gt;  
26                 &lt;mx:DataGridColumn headerText="价格" dataField="Price"/&gt;  
27             &lt;/mx:columns&gt;  
28         &lt;/mx:DataGrid&gt;  
29         &lt;mx:ControlBar height="42"&gt;  
30             &lt;mx:Button label="加载数据" fontWeight="normal" click="onClick()"/&gt;  
31         &lt;/mx:ControlBar&gt;  
32     &lt;/mx:Panel&gt;  
33 &lt;/mx:Application&gt;  
34  
 

     本示例的运行结果如下图：

       ![](http://www.xueit.com/eimg/uploadfile/downpig/20092/09214231124179.jpg)

 

关于URLLoader的更多资料大家可以查看Adobe提供的在线文档：[http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/URLLoader.html](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/URLLoader.html)

文章来自学IT网：[http://www.xueit.com/html/2009-02/21\_574\_00.html](http://www.xueit.com/html/2009-02/21_574_00.html)