---
title: "纯AS3下访问WebService方法总汇"
author: "wgcode"
date: "2011-01-13T10:17:08Z"
tags: []
categories: ["编程语言"]
slug: "as3-webservice"
draft: false
lastmod: "2011-01-13T10:17:08Z"
id: 869998
url: "https://tts.iteye.com/blog/869998"
---

今天介绍一下纯AS3下访问WebService的方法...

如果你说Flex就已经身带了这个类..  
或者有第三方的类..  
那可以不用继续往下看..因为我不是介绍"WebService类的使用方法"..  
需要的请自行搜索相应的结果..或看自己看帮助..  
谢谢合作..

至于WebService的概念我就不多说了..不明白的Google或Baidu一下就行了..

今天我们会用以下的WebService来作一系列的测试,该ws可以返回指定手机号码的归属..  
由[http://www.webxml.com.cn/](/admin/blogs/link.php?url=http%3A%2F%2Fwww.webxml.com.cn%2F) 提供..  
该网站上有很多实用的ws..

[http://www.webxml.com.cn/WebServices/MobileCodeWS.asmx](/admin/blogs/link.php?url=http%3A%2F%2Fwww.webxml.com.cn%2FWebServices%2FMobileCodeWS.asmx)  
我们先打开上面的地址

看到页面中介绍了该ws的两个方法

> getDatabaseInfo  
> 获得国内手机号码归属地数据库信息  
> 输入参数：无；  
> 返回数据：一维字符串数组（省份 城市 记录数量）。
> 
> getMobileCodeInfo  
> 获得国内手机号码归属地省份、地区和手机卡类型信息  
> 输入参数：mobileCode = 字符串（手机号码，最少前7位数字），userID = 字符串（商业用户ID） 免费用户为空字符串；  
> 返回数据：字符串（手机号码：省份 城市 手机卡类型）。

我们以下的测试会以getMobileCodeInfo为例子来进行..  
方法名getMobileCodeInfo,需要两个参数..  
一个为mobileCode,即手机号码,下面的例子均使用13800138000  
第二为userID,留空即可

方法1:GET  
有部份的ws支持GET方法.对于这类型的ws.我们可以直接使用get方式来获取数据  
格式为:WS地址/方法?参数=值\[&参数=值...]

像上面的方式..  
我们直接拼接这样一个URL地址:  
[http://www.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=13800138000&userID=](/admin/blogs/link.php?url=http%3A%2F%2Fwww.webxml.com.cn%2FWebServices%2FMobileCodeWS.asmx%2FgetMobileCodeInfo%3FmobileCode%3D13800138000%26amp%3BuserID%3D)  
即可直接访问..浏览器打开后显示  
![纯AS3下访问WebService方法总汇](http://idea.l4cd.net/blog/post/post-old-128/ws000.jpg "纯AS3下访问WebService方法总汇")

在AS3中..我们使用URLLoader来加载..代码如下:

 

```

package {
02.    import flash.display.Sprite;
03.    import flash.events.Event;
04.    import flash.net.URLLoader;
05.    import flash.net.URLRequest;
06.  
07.    public class WSExample extends Sprite
08.    {
09.          
10.        public function WSExample()
11.        {
12.            init();
13.        }
14.        private function init():void
15.        {
16.            var loader:URLLoader = new URLLoader()
17.            loader.addEventListener(Event.COMPLETE,complete);
18.            loader.load(new URLRequest("http://www.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode=13800138000&;userID="))
19.        }
20.        private function complete(e:Event):void
21.        {
22.            trace(XML(e.target.data))//13800138000：北京 北京 北京移动全球通卡
23.        }
24.    }
25.}

 
```

 

方法2:POST  
此方法和上面的GET一样..只有部份的ws支持..调用方法基本和上面的GET一样..  
只是把方法的参数以POST的形式发送  
在AS3中..我们还是使用URLLoader..代码如下:

 

```

package {
02.    import flash.display.Sprite;
03.    import flash.events.Event;
04.    import flash.net.URLLoader;
05.    import flash.net.URLRequest;
06.    import flash.net.URLRequestMethod;
07.  
08.    public class WSExample2 extends Sprite
09.    {
10.          
11.        public function WSExample2()
12.        {
13.            init();
14.        }
15.          
16.        private function init():void
17.        {
18.            var loader:URLLoader = new URLLoader()
19.            loader.addEventListener(Event.COMPLETE,complete);
20.              
21.            var request:URLRequest = new URLRequest("http://www.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo")
22.            request.method = URLRequestMethod.POST;
23.            request.data = "mobileCode=13800138000&userID="
24.            loader.load(request)
25.        }
26.        private function complete(e:Event):void
27.        {
28.            trace(XML(e.target.data))//13800138000：北京 北京 北京移动全球通卡
29.        }
30.    }
31.}

 
```

 

方法3:常规访问  
此方法中..我们使用常规的方法来访问WS,所有的WS都适用..  
PS:暂时只有 http://www.webxml.com.cn/ 的WS做测试..(不懂后台..所以无法自己写WS测试..),如各位发现问题..可回复指出..

首先..我们使用FLEX中的WS类写一个调用上述WS的程序..然后通过程序截获数据..  
首先Head中信息为..

 

```
(Request-Line)  POST /WebServices/MobileCodeWS.asmx HTTP/1.1
02.Accept  */*
03.Accept-Encoding  gzip, deflate
04.Accept-Language  zh-CN
05.Cache-Control  no-cache
06.Connection  Keep-Alive
07.Content-Length  375
08.Content-Type  text/xml; charset=utf-8
09.Cookie  WebXmlCookies=WeatherProvince=31124&WeatherCity=2419; ASP.NET_SessionId=qvrl3z45fqbngw55mdjysp3m; __utma=89798685.2765186755903630000.1237825717.1237861008.1237903668.4; __utmz=89798685.1237825717.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=89798685.1.10.1237903668; __utmc=89798685
10.Host  www.webxml.com.cn
11.SOAPAction  "http://WebXml.com.cn/getMobileCodeInfo"
12.User-Agent  Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; Trident/4.0; QQDownload 1.7; TencentTraveler 4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)
13.x-flash-version  10,0,22,87
```

 

POST内容为

```
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
2.  <SOAP-ENV:Body>
3.    <tns:getMobileCodeInfo xmlns:tns="http://WebXml.com.cn/">
4.      <tns:mobileCode>13800138000</tns:mobileCode>
5.    </tns:getMobileCodeInfo>
6.  </SOAP-ENV:Body>
```

   
分析其中POST内容..发现为一个XML格式字符串请求..  
格式为  
其中  
getMobileCodeInfo为方法名  
mobileCode为参数  
13800138000为mobileCode的值  
http://WebXml.com.cn/为该ws的Namespace  
tns为任意名字..这里为tns(targetNamespace简写?)

知道格式后..我们就可以开始在AS3里拼接这些数据..然后访问WS

代码如下:

```
package {
02.    import flash.display.Sprite;
03.    import flash.events.Event;
04.    import flash.net.URLLoader;
05.    import flash.net.URLRequest;
06.    import flash.net.URLRequestHeader;
07.    import flash.net.URLRequestMethod;
08.  
09.    public class WSExample3 extends Sprite
10.    {
11.          
12.        public function WSExample3()
13.        {
14.            init();
15.        }
16.          
17.        private function init():void
18.        {
19.            //拼接XML
20.            var s:XML = <SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
21.                            <SOAP:Body>
22.                                <tns:getMobileCodeInfo xmlns:tns="http://WebXml.com.cn/">
23.                                    <tns:mobileCode>13800138000</tns:mobileCode>
24.                                    <tns:userID></tns:userID>
25.                                </tns:getMobileCodeInfo>
26.                            </SOAP:Body>
27.                        </SOAP:Envelope>
28.            //注意tns,getMobileCodeInfo,mobileCode,userID
29.              
30.              
31.            var request:URLRequest = new URLRequest("http://www.webxml.com.cn/WebServices/MobileCodeWS.asmx")
32.            request.method = URLRequestMethod.POST;
33.              
34.            //添加requestHeaders,经测试和网上资料,只添加Content-Type和SOAPAction即可
35.            //Content-Type发送内容的格式..
36.            //SOAPAction由该ws的Namespace+方法组成..
37.            var headers:Array = [];
38.            headers.push(new URLRequestHeader("Content-Type", "text/xml; charset=utf-8"));
39.            headers.push(new URLRequestHeader("SOAPAction", "http://WebXml.com.cn/getMobileCodeInfo"));
40.            request.requestHeaders = headers;
41.  
42.            //指定请求内容
43.            request.data = s.toXMLString();
44.              
45.            var loader:URLLoader = new URLLoader();
46.            loader.addEventListener("complete", complete);
47.            loader.load(request)
48.        }
49.        private function complete(e:Event):void
50.        {
51.            trace(XML(e.target.data))
52.            //输出:
53.            //<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
54.            //  <soap:Body>
55.            //    <getMobileCodeInfoResponse xmlns="http://WebXml.com.cn/">
56.            //      <getMobileCodeInfoResult>13800138000：北京 北京 北京移动全球通卡</getMobileCodeInfoResult>
57.            //    </getMobileCodeInfoResponse>
58.            //  </soap:Body>
59.            //</soap:Envelope>
60.            //其中getMobileCodeInfoResult为我们需要的结果
61.        }
62.    }
63.}
```

 

方法4:自定义WebService类  
经过方法三..我们已经知道了WebService的访问实现原理..  
不过实现起来非常麻烦..需要手动去写方法名..参数名..ns等

其实这些信息..都在ws中有描述..  
Flex的类和第三方的WebService类也是通过不同的手段..  
最后生成请求的XML..  
以方便的访问WS..

以Flex的WebService为例..  
首先访问 地址?WSDL  
如[http://www.webxml.com.cn/WebServices/MobileCodeWS.asmx?WSDL](/admin/blogs/link.php?url=http%3A%2F%2Fwww.webxml.com.cn%2FWebServices%2FMobileCodeWS.asmx%3FWSDL)  
获取方法及相应的参数名..(types.schema.element即是相应的方法,每个element下为参数)  
获取ns(types.schema中的@targetNamespace??)  
然后调用相应方法的时候就可以自动拼接请求内容和requestHeaders中的SOAPAction  
再进行访问

当中还可以继承flash.utils.Proxy..  
并重写callProperty..  
即可实现像Flex的WebService在中的..  
webService.方法名(...参数)这样的调用格式..  
详细参数flash.utils.Proxy...