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())
Probably a length mismatch between the character length of
xml.InnerXml
and what is actually written to the stream inxml.Save(newStream)
. Check ifInnerXml
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.