REstful POST:写入流的字节数超过指定的Content-Length字节数

本文关键字:字节数 Content-Length POST REstful | 更新日期: 2023-09-27 18:08:44

抛出这个错误

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

,当我运行下面的代码:

var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = Encoding.UTF8.GetByteCount(json);
using (var webStream = request.GetRequestStream())
using (var requestWriter = new StreamWriter(webStream, System.Text.Encoding.UTF8))
{
    requestWriter.Write(json);
}

我读到,当方法是HEAD或GET时,错误可能发生,但这里是POST。

你知道这是怎么回事吗?

REstful POST:写入流的字节数超过指定的Content-Length字节数

问题是您首先编写UTF-8 BOM,因为Encoding.UTF8默认是这样做的。简短但完整的示例:

using System;
using System.IO;
using System.Text;
class Test
{
    static void Main()
    {
        string text = "text";
        var encoding = Encoding.UTF8;
        Console.WriteLine(encoding.GetByteCount(text));
        using (var stream = new MemoryStream())
        {
            using (var writer = new StreamWriter(stream, encoding))
            {
                writer.Write(text);
            }
            Console.WriteLine(BitConverter.ToString(stream.ToArray()));
        }
    }
}
输出:

4
EF-BB-BF-74-65-78-74

最简单的修复方法是或者将序言长度添加到内容长度中,使用没有BOM的编码:

Encoding utf8NoBom = new UTF8Encoding(false);

用这个代替Encoding.UTF8,一切都会好起来的。