抛出此错误
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);
}
我读过,当Method是HEAD或GET时可能会发生错误,但这里是POST。
知道那里有什么问题吗?
答案 0 :(得分:9)
问题在于您首先要编写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
,一切都应该好。