简化ASP页面调用WebService

在开发ASP页面时,经常需要调用WebService。这个过程可能会遇到一些挑战,尤其是对于初学者来说。本文将介绍如何通过VBScript类简化这一过程。

首先,需要创建一个VBScript类,该类封装了调用WebService的逻辑。这个类提供了一些属性,如URL、方法名、参数和响应,使得调用WebService变得非常简单。

以下是使用这个VBScript类的示例页面:

<%@ Language=VBScript %> <%@ Import Namespace="System.Collections" %> <% Option Explicit %> <!--#include virtual="/webservice.asp"--> <html> <head> <title>testws</title> </head> <body> <% Dim ws Set ws = New WebService ws.url = "http://localhost/yourwebservice.asmx" ws.method = "MethodName" ws.parameters.Add "ParamName1", 1 ws.parameters.Add "ParamName2", 300 ws.parameters.Add "ParamNameN", 500 ws.execute Response.Write ws.response Set ws = Nothing %> </body> </html>

如所见,使用这个类非常简单:定义属性,调用execute方法,然后response属性将返回WebService的信息。

<% Option Explicit %> Class WebService Public Url Public Method Public Response Public Parameters Public Function execute() Dim xmlhttp Set xmlhttp = CreateObject("Microsoft.XMLHTTP") xmlhttp.Open "POST", Url & "/" & Method, False xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded" xmlhttp.Send Parameters.toString Response = xmlhttp.responseText Set xmlhttp = Nothing End Function Private Sub Class_Initialize() Set Parameters = New wsParameters End Sub Private Sub Class_Terminate() Set Parameters = Nothing End Sub End Class Class wsParameters Public mCol Public Function toString() Dim nItem Dim buffer buffer = "" For nItem = 1 To Count buffer = buffer & Item(nItem).toString & "&" Next If Right(buffer, 1) = "&" Then buffer = Left(buffer, Len(buffer) - 1) End If toString = buffer End Function Public Sub Clear Set mcol = Nothing Set mCol = CreateObject("Scripting.Dictionary") End Sub Public Sub Add(pKey, pValue) Dim newParameter Set newParameter = New wsParameter newParameter.Key = pKey newParameter.Value = pValue mCol.Add mCol.count + 1, newParameter Set newParameter = Nothing End Sub Public Function Item(nKey) Set Item = mCol.Item(nKey) End Function Public Function ExistsXKey(pKey) Dim nItem For nItem = 1 To mcol.count If mCol.Item(nItem).key = pKey Then ExistsXKeyword = True Exit For End If Next End Function Public Sub Remove(nKey) mCol.Remove(nKey) End Sub Public Function Count() Count = mCol.count End Function Private Sub Class_Initialize() Set mCol = CreateObject("Scripting.Dictionary") End Sub Private Sub Class_Terminate() Set mCol = Nothing End Sub End Class Class wsParameter Public Key Public Value Public Function toString() toString = Key & "=" & Value End Function End Class
沪ICP备2024098111号-1
上海秋旦网络科技中心:上海市奉贤区金大公路8218号1幢 联系电话:17898875485