在flash as3项目中调用 web service

flash as3的类库默认不支持web service,要在as3项目中使用web service,则必须将flex的sdk中相关类库(swc)拷贝至项目中,并引用。


1、在fd 中创建as3项目



2、把flex sdk中的swc全部拷贝至项目文件夹中,并引用。

这里懒得研究到底需要哪些swc了



3、调用过程

由于web service对外公开了wsdl,在调用过程中,此wsdl需要在flash中缓存一次,等加载这个wsdl完毕就可以调用web service中的方法了

(1)加载wsdl
//////////////定义属性
private var _service:WebService;

//////////////////////////////构造函数

_service = new WebService(url);
   _service.addEventListener(LoadEvent.LOAD,onWSDL);
   _service.addEventListener(FaultEvent.FAULT, onFaultWsdl);

 

 //////////////////////////////////////////事件处理

private function onFaultWsdl(e:FaultEvent):void 
  {
      
  }
  
  private function onWSDL(e:LoadEvent):void 
  {
       //此时可以调用方法了
  }




(2)调用方法:

///////////////////////////////////////////////////////

private var callObject:Operation;


///////////////////////////////////////////////////////

callObject = _service['funName'];  //funName为调用方法的名字
 callObject.addEventListener(ResultEvent.RESULT, onResult);

CallObject.addEventListener(FaultEvent.FAULT, onFault);

 callObject.send.apply(null, [param0,param1,param2,...]);   //param0,param1,param2,...为调用参数

 

//处理调用错误

private function onFault(e:FaultEvent):void 
  {
   
  }
  

//处理调用结果
  private function onResult(e:ResultEvent):void 
  {
       trace(e.result);
  }



完整代码:



package  
{
	import flash.display.Sprite;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.soap.LoadEvent;
	import mx.rpc.soap.Operation;
	import mx.rpc.soap.WebService;
	/**
	 * ...
	 * @author Randy
	 */
	public class TestWebservice extends Sprite 
	{
		private var _service:WebService;
		private var _callObject:Operation;
		
		
		public function TestWebservice() 
		{
			_service = new WebService;
			_service.addEventListener(LoadEvent.LOAD,onWSDL);
			_service.addEventListener(FaultEvent.FAULT, onFaultWsdl);
			_service.loadWSDL("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl");
		}
		
		
		private function onFaultWsdl(e:FaultEvent):void 
		{
			trace("加载wsdl失败: "+e.message);
		}
		
		private function onWSDL(e:LoadEvent):void 
		{
			_callObject = _service["getSupportProvince"];
			_callObject.addEventListener(ResultEvent.RESULT, onResult);
			_callObject.addEventListener(FaultEvent.FAULT, onFault);
			_callObject.send.apply(null,null);
		}
		
		
		
		private function onFault(e:FaultEvent):void 
		{
			trace("调用webservice失败: " + e.message);
		}
		
		private function onResult(e:ResultEvent):void 
		{
			trace("省份: " + e.result);
			
			var provs:Array = String(e.result).split(",");
			
			
			_callObject = _service["getSupportCity"];
			_callObject.addEventListener(ResultEvent.RESULT, onResultCity);
			_callObject.addEventListener(FaultEvent.FAULT, onFault);
			_callObject.send.apply(null,[provs[2]]);
		}
		
		private function onResultCity(e:ResultEvent):void 
		{
			trace("地区:" + e.result);
		}
		
		
		
	}

}

你可能感兴趣的:(webservice)