摘要:不加入Web參考,使用 HttpWebRequest+HttpWebResponse 取得WebService的回傳值
很多人都會使用Web參考加入WebService,可是當主管說不希望這麼做的時後怎麼辦
這時就要利用 System.Net 的類別
以下是實做過程
寫一個簡單的WebService:
Public Function HelloWorld() Function HelloWorld(ByVal recStr As String) As String
'經過編碼,所以接回來要解碼
Dim tmp As String = Server.UrlDecode(recStr)
Return "這是從WebService傳回來的字串:" & tmp
End Function
首先參考WebService網頁所提供的範例(原則上是照抄)
接下來開一個簡單的WindowForm專案,放入一個 BUTTON,跟 TEXTBOX
記得要先加入參考:(手動加入)
Imports System.Web
Imports System.Xml
Button的程式:
Dim req As HttpWebRequest
Dim reps As HttpWebResponse
Dim url As String = ""
Dim reqStr As String = ""
Try
'WebService的網址
url = "http://localhost/myWeb/PrintStr.asmx "
req = CType(System.Net.HttpWebRequest.Create(url), HttpWebRequest)
req.ContentType = "application/soap+xml; charset=utf-8"
req.Method = "POST"
reqStr = "<?xml version=""1.0"" encoding=""utf-8""?>"
reqStr &= "<soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">"
reqStr &= "<soap12:Body>"
'方法名稱
reqStr &= "<HelloWorld xmlns=""http://tempuri.org/"">"
'重點:參數名稱跟傳入的值, 如果有特殊字最好要編碼
reqStr &= "<recStr>" & HttpUtility.UrlEncode(Me.txtMsg.Text) & "</recStr>"
reqStr &= "</HelloWorld>"
reqStr &= "</soap12:Body>"
reqStr &= "</soap12:Envelope>"
'串出來的字串長度
req.ContentLength = reqStr.Length
'寫入資料流
Dim sw As New IO.StreamWriter(req.GetRequestStream, System.Text.Encoding.Default)
sw.Write(reqStr)
sw.Close()
reps = CType(req.GetResponse, HttpWebResponse)
'取回資料流
Dim sr As New IO.StreamReader(reps.GetResponseStream)
'宣告一個xml文件載入回傳的字串 ,回傳的資料會是一份xml文件
Dim xmlDoc As New XmlDocument
xmlDoc.Load(sr)
'取得第一個節點的innerText
Me.TextBox1.Text = xmlDoc.ChildNodes(1).FirstChild.InnerText
sr.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString())
End Try
End Sub