REstful POST : Bytes to be written to the stream exceed the Content-Length bytes size specified

匿名 (未验证) 提交于 2019-12-03 00:56:02

问题:

This error gets thrown

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

when I run the following code:

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

I read, that error could occurs when Method was HEAD or GET, but here it's POST.

Any idea what's wrong there?

回答1:

The problem is that you're writing the UTF-8 BOM first, because Encoding.UTF8 does that by default. Short but complete example:

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 

The simplest fix is either to add the preamble size to the content length, or to use an encoding which doesn't have a BOM:

Encoding utf8NoBom = new UTF8Encoding(false); 

Use that instead of Encoding.UTF8, and all should be well.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!