0

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

John Saunders
  • 160,644
  • 26
  • 247
  • 397
doremi
  • 14,921
  • 30
  • 93
  • 148

1 Answers1

1

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
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I need the Content-Length Header. It is required by the API. – doremi Feb 19 '11 at 14:43
  • @Joshua McGinnis, the `Content-Length` request header is automatically set by the `WebClient` based on the length of the data you are sending. So with my example XML, `Content-Length: 14` will be sent in the request. Never try to set this header manually as you might get inconsistent results and violate the HTTP protocol specification. – Darin Dimitrov Feb 19 '11 at 14:57
  • I did not know that! How would I print all of the headers so I can this? – doremi Feb 19 '11 at 16:42
  • @Joshua McGinnis, you could [enable tracing](http://stackoverflow.com/questions/3590650/see-httpwebrequest-as-string-before-getresponse-without-using-fiddler/3590658#3590658) in your application or install a network analyzer such as [Fiddler](http://www.fiddler2.com/fiddler2/). – Darin Dimitrov Feb 19 '11 at 16:45