REstful POST :要写入流的字节超过指定的 Content-Length 字节大小 [英] REstful POST : Bytes to be written to the stream exceed the Content-Length bytes size specified

查看:40
本文介绍了REstful POST :要写入流的字节超过指定的 Content-Length 字节大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抛出这个错误

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.

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

知道有什么问题吗?

推荐答案

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

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

输出:

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

最简单的解决方法是将前导码大小添加到内容长度,使用没有 BOM 的编码:

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

使用它代替 Encoding.UTF8,一切都会好起来的.

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

这篇关于REstful POST :要写入流的字节超过指定的 Content-Length 字节大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆