如何使用 VB.Net 将 XML 文档发布到 HTTP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5048753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to post XML document to HTTP with VB.Net
提问by doremi
I'm looking for help with posting my XML document to a url in VB.NET. Here's what I have so far ...
我正在寻求将我的 XML 文档发布到 VB.NET 中的 url 的帮助。这是我到目前为止...
Public Shared xml As New System.Xml.XmlDocument()
Public Shared Sub Main()
Dim root As XmlElement
root = xml.CreateElement("root")
xml.AppendChild(root)
Dim username As XmlElement
username = xml.CreateElement("username")
username.InnerText = _username
root.AppendChild(username)
xml.Save(Console.Out)
Dim url = "https://mydomain.com"
Dim req As WebRequest = WebRequest.Create(url)
req.Method = "POST"
req.ContentType = "application/xml"
req.Headers.Add("Custom: API_Method")
Console.WriteLine(req.Headers.ToString())
This is where things go awry:
这就是事情出错的地方:
I want to post the xml, and then print the results to console.
我想发布 xml,然后将结果打印到控制台。
Dim newStream As Stream = req.GetRequestStream()
xml.Save(newStream)
Dim response As WebResponse = req.GetResponse()
Console.WriteLine(response.ToString())
End Sub
回答by doremi
This is essentially what I was after:
这基本上是我所追求的:
xml.Save(req.GetRequestStream())
回答by Alain Pannetier
If you don't want to take care about the length, it is also possible to use the WebClient.UploadData method.
如果不想关心长度,也可以使用 WebClient.UploadData 方法。
I adapted your snippet slightly in this way.
我以这种方式稍微调整了您的代码段。
Imports System.Xml
Imports System.Net
Imports System.IO
Public Module Module1
Public xml As New System.Xml.XmlDocument()
Public Sub Main()
Dim root As XmlElement
root = xml.CreateElement("root")
xml.AppendChild(root)
Dim username As XmlElement
username = xml.CreateElement("username")
username.InnerText = "user1"
root.AppendChild(username)
Dim url = "http://mydomain.com"
Dim client As New WebClient
client.Headers.Add("Content-Type", "application/xml")
client.Headers.Add("Custom: API_Method")
Dim sentXml As Byte() = System.Text.Encoding.ASCII.GetBytes(xml.OuterXml)
Dim response As Byte() = client.UploadData(url, "POST", sentXml)
Console.WriteLine(response.ToString())
End Sub
End Module