[英]System.Net.ProtocolViolationException:Bytes to be written to the stream exceed the Content-Length bytes size specified
[英]REstful POST : 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.
當我運行以下代碼時:
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。
知道那里有什么問題嗎?
問題是您首先編寫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
,一切都應該很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.