ASP调用Web Services示例

<%
'功能: 调用Web Services
'参数:
'        url        Web Services地址
'        method    要调用的方法名称
'        args    传递给method方法的参数(值/对格式)
'返回: xml字符串
Function WebServices(url,method,args)
    Dim xmlHttp,sUrl
    Set xmlHttp = CreateObject("MSXML2.XMLHTTP")
    sUrl = url & "/" & method
    xmlHttp.Open "post",sUrl,false
    xmlHttp.SetRequestHeader "Content-Type","application/x-www-form-urlencoded"
    xmlHttp.Send(args)
    If xmlHttp.Status = 200 Then
        WebServices = xmlHttp.responseXML.xml
    End If
    Set xmlHttp = Nothing
End Function

'调用示例:
'    Web Services:http://www.webxml.com.cn/WebServices/WeatherWS.asmx
'    getWeather方法:public string[] getWeather(string theCityCode, string theUserID);
Response.Write(WebServices("http://www.webxml.com.cn/WebServices/WeatherWS.asmx","getWeather","theCityCode=2210&theUserID="))
%>

还有一种方法是使用微软的SOAP Toolkit 3.0,代码如下:

<%
Dim soap
Set soap = CreateObject("MSSOAP.SoapClient30")
soap.ClientProperty("ServerHTTPRequest") = True
soap.mssoapinit "http://www.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl", "","",""
Response.Write(soap.getMobileCodeInfo("13799438732",""))
Set soap = Nothing
%>

但使用SOAP Toolkit 3.0的缺点是必须在服务器上安装后才能使用!

-------------------------------------- 2009-05-24 补充 --------------------------------------
1).必须在Web Services项目配置文件(web.config)的system.web节点中添加以下内容:
<webServices>
  <protocols>
    <add name="HttpPost"/>
    <add name="HttpGet"/>
  </protocols>
</webServices>

否则,http://www.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather?theCityCode=2210&theUserID=调用时会提示:因 URL 意外地以“/getWeather”结束,请求格式无法识别。

2).使用C#编写的Web Services对大小写是敏感的,所以调用的方法名一定要注意大小写,否则会出错。

3).如果参数值带中文,一定要注意编码,否则可能得不到你想要的结果。

评论: 0 | 引用: 0 | 查看次数: 4401
发表评论
登录后再发表评论!