Question

Ugh, I keep getting a ProtocolViolationException "Bytes to be written to the stream exceed the Content-Length bytes size specified." on the following code.

I've tried setting Content-Length numerous ways with no success.

Dim url = "https://domain.com"
Dim req As WebRequest = WebRequest.Create(url)
req.Method = "POST"
req.ContentType = "application/xml"

Dim utf8 As New UTF8Encoding()
req.ContentLength = utf8.GetByteCount(xml.OuterXml) 

xml.Save(req.GetRequestStream()) // throws the exception
req.GetRequestStream().Close()

Dim httpResp As WebResponse = req.GetResponse()
Dim stReader As StreamReader = New StreamReader(httpResp.GetResponseStream())
Dim strResponse As String

strResponse = stReader.ReadToEnd()

Console.WriteLine(strResponse)

I've tried setting the content-length using xml.OutXML.Length

Was it helpful?

Solution

Try with a WebClient, it makes the code easier and it takes care of properly flushing and disposing all the streams:

Dim xml As New XmlDocument
xml.LoadXml("<foo>abc</foo>")
Using client As WebClient = New WebClient
    client.Headers.Item(HttpRequestHeader.ContentType) = "application/xml"
    Dim data As Byte() = Encoding.UTF8.GetBytes(xml.OuterXml)
    Console.WriteLine(Encoding.UTF8.GetString(client.UploadData("https://domain.com", data)))
End Using
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top