Search code examples
xmlvb.netxmlhttprequestwebrequestwebresponse

You must write ContentLength bytes to the request stream before calling [Begin]GetResponse


Error: You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.

Can anyone advise why I am getting the above error when running the following code

        Dim xml As New System.Xml.XmlDocument()

        Dim root As XmlElement
        root = xml.CreateElement("root")
        xml.AppendChild(root)

        Dim username As XmlElement
        username = xml.CreateElement("UserName")
        username.InnerText = "xxxxx"
        root.AppendChild(username)

        Dim password As XmlElement
        password = xml.CreateElement("Password")
        password.InnerText = "xxxx"
        root.AppendChild(password)

        Dim shipmenttype As XmlElement
        shipmenttype = xml.CreateElement("ShipmentType")
        shipmenttype.InnerText = "DELIVERY"
        root.AppendChild(shipmenttype)


        Dim url = "xxxxxx"
        Dim req As WebRequest = WebRequest.Create(url)
        req.Method = "POST"
        req.ContentType = "application/xml"
        req.Headers.Add("Custom: API_Method")
        req.ContentLength = xml.InnerXml.Length

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

        Dim response As WebResponse = req.GetResponse()


        Console.Write(response.ToString())

Solution

  • Probably a length mismatch between the character length of xml.InnerXml and what is actually written to the stream in xml.Save(newStream). Check if InnerXml includes the xml version node, for example. Also, I don't see you specifying a character encoding, which definitely affects the size on the wire. Perhaps you need to save to a temporary memory stream, get the length of that, and then send that in the request.