我试图使用XML Web服务。该服务是基于asterix的PBX,称为switchvox。每个请求都应采用XML格式,并在响应中返回XML。我的代码如下,我只能让API返回一个错误,说我的请求是空的。
Dim xml As String
xml = ""
xml = xml & " <request method=""switchvox.users.extensions.getInfo"">"
xml = xml & " <parameters>"
xml = xml & " <extensions>"
xml = xml & " <extension>104</extension>"
xml = xml & " </extensions>"
xml = xml & " </parameters>"
xml = xml & " </request>"
Dim url As String = "https://pbx/xml"
Dim webRequest__1 As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
webRequest__1.Method = "POST"
webRequest__1.Credentials = New NetworkCredential("user", "pass")
webRequest__1.ContentType = "text/xml"
webRequest__1.ContentLength = xml.Length
Using requestWriter2 As New StreamWriter(webRequest__1.GetRequestStream())
requestWriter2.Write(xml)
End Using
Dim resp As HttpWebResponse = DirectCast(webRequest__1.GetResponse(), HttpWebResponse)
Dim responseData As String = String.Empty
Using responseReader As New StreamReader(webRequest__1.GetResponse().GetResponseStream())
responseData = responseReader.ReadToEnd()
End Using
答案 0 :(得分:1)
不要使用字符串操作(包括连接)来生成XML。始终使用XML API,如LINQ to XML。您很幸运使用VB.NET,因为您可以使用XML Literals功能轻松构建XML,并且更可能正确。尝试这样的事情:
Public Function GetInfo() As XElement
Dim xml As XElement = <request method="switchvox.users.extensions.getInfo">
<parameters>
<extensions>
<extension>104</extension>
</extensions>
</parameters>
</request>
Const url As String = "https://pbx/xml"
Dim webRequest__1 As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
webRequest__1.Method = "POST"
webRequest__1.Credentials = New NetworkCredential("user", "pass")
webRequest__1.ContentType = "text/xml"
webRequest__1.ContentLength = xml.ToString().Length
Using requestWriter2 As New StreamWriter(webRequest__1.GetRequestStream())
requestWriter2.Write(xml.ToString())
End Using
Using resp As HttpWebResponse = DirectCast(webRequest__1.GetResponse(), HttpWebResponse)
Using responseStream = resp.GetResponseStream()
Return XElement.Load(responseStream)
End Using
End Using
End Function