开发者

How to post XML document to HTTP with VB.Net

开发者 https://www.devze.com 2023-02-11 20:25 出处:网络
I\'m looking for help with posting my XML document to a url in VB.NET. Here\'s what I have so far ...

I'm looking for help with posting my XML document to a url in VB.NET. Here's what I have so far ...

  Public Shared xml As New System.Xml.XmlDocument()

    Public Shared Sub Main()

        Dim root As XmlElement
        root = xml.CreateEle开发者_高级运维ment("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.

        Dim newStream As Stream = req.GetRequestStream()
        xml.Save(newStream)

        Dim response As WebResponse = req.GetResponse()
        Console.WriteLine(response.ToString())
 End Sub


This is essentially what I was after:

xml.Save(req.GetRequestStream())


If you don't want to take care about the length, it is also possible to use the WebClient.UploadData method.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号