我似乎无法弄清楚为什么总是出现以下错误:

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);
        }
    }

最佳答案

有三种可能的选择

  • 按照answer from @rene
  • 中所述修复ContentLength
  • 不要设置ContentLength,HttpWebRequest正在缓冲数据,并自动设置ContentLength。
  • 将SendChunked属性设置为true,而不设置ContentLength。该请求将编码的块发送到Web服务器。 (需要HTTP 1.1,并且必须由Web服务器支持)

  • 代码:
    ...
    request.SendChunked = true;
    using (Stream writeStream = request.GetRequestStream())
    { ... }
    

    10-06 00:07