抛出此错误
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。
知道那里出了什么问题吗?
问题是你先写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()));
}
}
}
Output:
4
EF-BB-BF-74-65-78-74
最简单的修复是either将前导码大小添加到内容长度中,or使用没有 BOM 的编码:
Encoding utf8NoBom = new UTF8Encoding(false);
用它代替Encoding.UTF8
,一切都应该很好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)