错误 (HttpWebRequest):要写入流的字节超过指定的 Content-Length 字节大小

Error (HttpWebRequest): Bytes to be written to the stream exceed the Content-Length bytes size specified

我似乎无法弄清楚为什么我不断收到以下错误:

Bytes to be written to the stream exceed the Content-Length bytes size specified.

在以下行:

writeStream.Write(bytes, 0, bytes.Length);

这是一个 Windows Forms 项目。如果有人知道这里发生了什么,我肯定会欠你一个。

    private void Post()
    {


        HttpWebRequest request = null;
        Uri uri = new Uri("xxxxx");
        request = (HttpWebRequest)WebRequest.Create(uri);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        XmlDocument doc = new XmlDocument();
        doc.Load("XMLFile1.xml");
        request.ContentLength = doc.InnerXml.Length;
        using (Stream writeStream = request.GetRequestStream())
        {
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] bytes = encoding.GetBytes(doc.InnerXml);
            writeStream.Write(bytes, 0, bytes.Length);
        }
        string result = string.Empty;

        request.ProtocolVersion = System.Net.HttpVersion.Version11;
        request.KeepAlive = false;
        try
        {
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (System.IO.StreamReader readStream = new System.IO.StreamReader(responseStream, Encoding.UTF8))
                    {
                        result = readStream.ReadToEnd();
                    }
                }
            }
        }
        catch (Exception exp)
        {
            // MessageBox.Show(exp.Message);
        }
    }

您的 InnerXml 中的编码字节数组可能更长,因为 UTF8 encoding 中的某些字符对于单个字符占用 2 或 3 个字节。

按如下方式更改您的代码:

    using (Stream writeStream = request.GetRequestStream())
    {
        UTF8Encoding encoding = new UTF8Encoding();
        byte[] bytes = encoding.GetBytes(doc.InnerXml);
        request.ContentLength = bytes.Length;
        writeStream.Write(bytes, 0, bytes.Length);
    }

要准确显示正在发生的事情,请在 LINQPad 中尝试此操作:

var s = "é";
s.Length.Dump("string length");
Encoding.UTF8.GetBytes(s).Length.Dump("array length");

这将输出:

 string length: 1 
 array length:  2 

现在使用不带撇号的 e

var s = "e";
s.Length.Dump("string length");
Encoding.UTF8.GetBytes(s).Length.Dump("array length");

这将输出:

string length: 1 
array length:  1 

所以请记住:字符串长度和特定编码所需的字节数可能不同。

存在三种可能的选择

  • 按照

  • 中所述修复 ContentLength
  • 不设置ContentLength,HttpWebRequest正在缓冲数据,自动设置ContentLength

  • 将 SendChunked 属性 设置为 true,并且不设置 ContentLength。请求被编码发送到网络服务器。 (需要 HTTP 1.1 并且必须得到网络服务器的支持)

代码:

...
request.SendChunked = true;
using (Stream writeStream = request.GetRequestStream())
{ ... }