65.9K
CodeProject 正在变化。 阅读更多。
Home

用于在 ASP 中使用 Web 服务的类实现

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.73/5 (11投票s)

2005年6月14日

CPOL
viewsIcon

135860

downloadIcon

755

使用这个类,你只需要设置几个属性就可以访问 Web 服务,只需要知道 Web 服务的 URL、要调用的方法和参数即可。

引言

最近,我第一次尝试从 ASP 页面使用 Web 服务,并且遇到了很多问题。经过几个小时的努力,我可以使用 Microsoft.XMLHTTP 从 ASP 访问我的 Web 服务,但代码并不容易理解(如果你是第一次使用),所以我决定将实现打包成一个简单的 VBScript 类,该类具有几个属性,可以用来访问 Web 服务。

使用该 VBScript 类的页面是

<!--#include virtual="/webservice.asp"-->
<html>
<head>
<title>testws</title>
</head>
<body>
<%
    dim ws
 
    set ws = new webservice
    ws.url = "https:///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 将返回来自 Web 服务的相关信息。

实现调用 Web 服务的类是

<%
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
%>

我希望我这个小小的实现代码能帮助到你,谢谢。如有任何问题,请发邮件给我

© . All rights reserved.