Vb.Net - 写入的字节超过 XML Post 中的内容长度字节

发布于 2024-10-17 22:01:15 字数 719 浏览 5 评论 0原文

呃,我不断收到 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 设置内容长度

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何处潇湘 2024-10-24 22:01:16

尝试使用 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文