×

通过Flash Remoting在Flash 中使用 Webservice

Kalet Kalet 发表于2009-08-11 14:08:49 浏览200 评论0

抢沙发发表评论

什么是 Webservice?

  在数字化的世界里,最重要的事情恐怕就是数据交换了。在 Webservice 出现以前每家公司都有自己的远程过程调用标准:微软用 COM,Java 用 Bean。不同厂商的产品之间很难做到相互交换数据。随着XML 的出现,人们发现 XML 这种语言,不仅有着通用的标准,同时又具有相当大的灵活性。用它作为数据交换的标准语言再合适不过了。于是,Webservice 就出现了。

  Webservice 与平台无关。无论你使用 .net 、Java 或者 Coldfusion。因为它是基于XML的。通过简单对象访问协议 SOAP 来调用它。想了解更过关于 Webservice 的情况,请参阅:http://www.zdnet.com.cn/developer/category/webservice 。

  找一个 Webservice!

  这里我们想在Flash中调用 Webservice,那么我么必须先去找一个。我推荐 http://www.xmethods.net 这个网站提供大量的免费 Webservice。其中一些相当有用也有趣。请打开下面这个网页
http://www.xmethods.net/ve2/ViewListing.po?key=uuid:477CEED8-1EDD-89FA-1070-6C2DBE1685F8  

  这个 Webservice 是提供美国的气温查询功能,只要你输入一个地区的邮政编码就可以得到当地的气温。大家可能注意到了这个 Webservice 的网址是:
http://www.xmethods.net/sd/2001/TemperatureService.wsdl  
那么,什么又是 WSDL 呢?WSDL 就是 Webservice 描述语言。这种语言就是以 XML 为基础的。好了,Webservice 已经到手。如何操作它呢?请点击 Analyze WSDL 来分析它。您也可以下载一个 XMLSpy,这个工具非常好。可以发现他有一个操作——getTemp。这个操作中,Input 参数是 Zipcode (邮政编码)。这就是我们要用到的方法。

  开始动手!

  打开Flash 新建一个文件。在第一帧上加入代码:
#include "NetServices.as"
#include "NetDebug.as"
if (init == null) {
init = true;
NetServices.setDefaultGatewayUrl("http://localhost:8500/flashservices/gateway");
gateway_conn = NetServices.createGatewayConnection();
myService = gateway_conn.getService("http://www.xmethods.net/sd/2001/TemperatureService.wsdl", this);
}

  这得注意的是这一句:myService = gateway_conn.getService("http://www.xmethods.net/sd/2001/TemperatureService.wsdl", this);
} 这里将Flash Remoting 网关连接到相应的 WSDL 上。

  接下来,我们设计界面,如图:
 



  上面的文本框用来输入邮政编码。是一个 Input Text。实例名称定义为 zipCode_txt。下面的文本框用来输出气温。是一个 Dynamic Text。实力名称为 getTemp_txt。最下面是一个按钮。Click Handler 定义为 doGet。注意,这些界面元素都放在第一帧上。

  我们打开第一帧的 ActionScript 面板。完成编码工作。需要添加的代码如下:
function doGet() {
myService.getTemp({zipcode:zipCode_txt.text});
getTemp_txt.text = "waiting";
}
function getTemp_Result(result) {
getTemp_txt.text = result;
}
stop();

  doGet 函数将 zipCode_txt 文本框中的邮政编码传递给 getTemp 操作。同时,先是一个提示信息 “waiting”,提示用户稍等。

  getTemp_Result 函数,将得到的结果显示到 getTemp_txt 文本框中。

  完整的代码如下:
#include "NetServices.as"
#include "NetDebug.as"
if (init == null) {
init = true;
NetServices.setDefaultGatewayUrl("http://localhost:8500/flashservices/gateway");
gateway_conn = NetServices.createGatewayConnection();
myService = gateway_conn.getService("http://www.xmethods.net/sd/2001/TemperatureService.wsdl", this);
}
function doGet() {
myService.getTemp({zipcode:zipCode_txt.text});
getTemp_txt.text = "waiting";
//myService.NewGame();
}
function getTemp_Result(result) {
getTemp_txt.text = result;
}
stop();

  好了,大功告成!测试的时候你可以打开 NetConnection Debugger 窗口,有助于调试。

  祝你成功!

群贤毕至

访客