在VB6或ASP中調用webservice

- 中國WEB開發者網絡 (http://www.webasp.net)
-- 技術教程 (http://www.webasp.net/article/)
--- 在VB6或ASP中調用webservice (http://www.webasp.net/article/12/11514.htm)
-- 作者:未知
-- 發佈日期: 2004-06-29
VB6或ASP中調用webservice



Web Services技術使異種計算環境之間可以共享數據和通信,達到信息的一致性。我們可以利用

HTTP POST/GET協議、SOAP協議來調用Web Services。



一、 利用SOAP協議在VB6中調用Web Services



; 首先利用.net發佈一個簡單的Web Services

<WebMethod()> _

Public Function getString(ByVal str As String) As String

Return "Hello World, " & str & "!"

End Function

該Web Services只包含一個getString方法,用於返回一個字符串。當我們調用這個Web Services時,發送給.asmx頁面的SOAP消息為:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://
schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<getString xmlns="http://tempuri.org/TestWebService/Service1">
<str>string</str>
</getString>
</soap:Body>
</soap:Envelope>
而返回的SOAP消息為:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="
http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<getStringResponse xmlns="http://tempuri.org/TestWebService/Service1">
<getStringResult>string</getStringResult>
</getStringResponse>
</soap:Body>
</soap:Envelope>

; 在VB6中調用這個簡單的Web Services可以利用利用XMLHTTP協議向.asmx頁面發

送SOAP來實現。

在VB6中,建立一個簡單的工程,界面如圖,我們通過點擊Button來調用這個簡

單的Web Services






Dim strxml As String

Dim str As String

str = Text2.Text

'定義soap消息

strxml = "<?xml version='1.0' encoding='utf-8'?><soap:Envelope

xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'

xmlns:xsd='http://www.w3.org/2001/XMLSchema'

xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><getString xmlns='http://tempuri.org/TestWebService/Service1'><str>" & str &

"</str></getString></soap:Body></soap:Envelope>"



'定義一個http對象,一邊向服務器發送post消息

Dim h As MSXML2.ServerXMLHTTP40

'定義一個XML的文檔對象,將手寫的或者接受的XML內容轉換成XML對像

Dim x As MSXML2.DOMDocument40

'初始化XML對像

Set x = New MSXML2.DOMDocument40

'將手寫的SOAP字符串轉換為XML對像

x.loadXML strxml

'初始化http對像

Set h = New MSXML2.ServerXMLHTTP40

'向指定的URL發送Post消息

h.open "POST", "http://localhost/TestWebService/Service1.asmx", False

h.setRequestHeader "Content-Type", "text/xml"

h.send (strxml)

While h.readyState <> 4

Wend

'顯示返回的XML信息

Text1.Text = h.responseText

'將返回的XML信息解析並且顯示返回值

Set x = New MSXML2.DOMDocument40

x.loadXML Text1.Text

Text1.Text = x.childNodes(1).Text



我們在TEXTBOX中輸入「中國」,再點擊BUTTON,於是就可以在下邊的TEXTBOX中顯示「Hello World, 中國」 。顯示如圖:


webasp.net