Vb.Net - 写入的字节超过XML Post中的Content-Length字节

时间:2011-02-19 06:38:07

标签: xml vb.net webrequest content-length

呃,我一直收到一个ProtocolViolationException“要写入流的字节超过指定的Content-Length字节大小。”在以下代码上。

我尝试过多种方式设置Content-Length但没有成功。

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)

我已尝试使用xml.OutXML.Length

设置内容长度

1 个答案:

答案 0 :(得分:1)

尝试使用WebClient,它使代码更容易,并负责正确刷新和处理所有流:

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