[ASP.NET] Call ASP.NET Web Service From ASP Sample Code

  • 3546
  • 0

[ASP.NET] Call ASP.NET Web Service From ASP Sample Code

這幾天遇到一個整合需求,需要提供客戶一個Sample Code 用來

Call ASP.NET Web Service ,而客戶的系統目前還是ASP撰寫且沒有這方面的

經驗,因此需要我們提供技術支援,但我也有點久沒寫ASP了,即然寫了Sample Code

因此就順手memo一下

 

基本上用ASP Call ASP.NET Web Service ,大致有二個方式

(1)以SOAP Toolkit來進行

(2)以XMLHTTP來進行

但由於以SOAP Toolkit來進行時需要額外安裝SOAP Toolkit,而且SOAP Toolkit已經

停止發展了,因此就直接選擇以XMLHTTP來進行

 

範例程式碼如下:


Dim xmlhttp
Dim parameters
Dim wsurl

'建立xmlhttp obj
Set xmlhttp = server.Createobject("MSXML2.XMLHTTP")

'ASP.NET Web Service所需參數
parameters="companycode=H&groupcode=420" 

'ASP.NET Web Service路徑
'若是有多個Methods,直接再加要呼叫的Method Name,以本例來說就是要呼叫service1.Exec Method
wsurl="http://localhost:20112/Services/Service1.asmx/Exec"

xmlhttp.Open "POST",wsurl,false
xmlhttp.setRequestHeader "Content-Type","application/x-www-form-urlencoded"
xmlhttp.send parameters

'判斷xmlhttp obj狀態
if xmlhttp.readystate=4 then

	....
	....
	....

end if

 

說明:

(1)XMLHTTP的狀態可由readyState Code判斷,共有五種情況

0

UNINITIALIZED
The object has been created, but not initialized (the open method has not been called).

1

LOADING
The object has been created, but the send method has not been called.

2

LOADED
The send method has been called, but the status and headers are not yet available.

3

INTERACTIVE
Some data has been received. Calling the responseBody and responseText properties at this state to obtain partial results will return an error, because status and response headers are not fully available.

4

COMPLETED
All the data has been received, and the complete data is available in the responseBody and responseText properties.

 

(2)執行狀態可由State Code判斷,一般來說若沒什麼錯誤則回傳200,其餘代碼則表示不同狀況

,可自行參考http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

 

(3)回傳的部份有二種方式可以使用

xmlhttp.responseText:視為一般字串
    xmlhttp.responseXML:視為 XMLDocument,可進一步使用Server.CreateObject("MSXML2.DOMDocument")

去解析

 

PS:以上範例程式碼沒有很嚴謹的判斷,取用時請視情況自行調整

 

Ref:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms753800(v=vs.85).aspx

http://msdn.microsoft.com/en-us/library/ms535874(v=VS.85).aspx

http://msdn.microsoft.com/zh-tw/library/ms537505(vs.85).aspx

http://www.w3.org/TR/XMLHttpRequest/

 

 

 

 

 

 

 

 

 

 

 

 

 

若本文對您有所幫助,歡迎轉貼,但請在加註【轉貼】及來源出處,並在附上本篇的超連結,感恩您的配合囉。

By No.18