gpt4 book ai didi

json - "Bytes to be written to the stream exceed the Content-Length bytes size specified"与 UTF8 编码的 json

转载 作者:行者123 更新时间:2023-12-04 22:14:00 27 4
gpt4 key购买 nike

我在向 Mandrill API 发送 JSON 对象时遇到编码问题。
使用 UTF8 编码写入流写入器时,抛出以下异常:

“要写入流的字节数超过了指定的 Content-Length 字节大小。”
紧接着:
“在写入所有字节之前无法关闭流。”

这是用于发送 JSON 对象的代码部分:

var httpWebRequest = (HttpWebRequest)WebRequest.Create(mandrillUrl + "/messages/send.json");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
var ser = new DataContractJsonSerializer(wrapper.GetType());
var ms = new MemoryStream();
ser.WriteObject(ms, wrapper);

var json = Encoding.UTF8.GetString(ms.ToArray());
httpWebRequest.ContentLength = json.Length;
var stream = httpWebRequest.GetRequestStream();

using (var strWriter = new StreamWriter(stream, Encoding.UTF8))
{
strWriter.Write(json);
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
}

在我看来,此错误与 UTF8 中的字节长度有关,但即使我将 httpWebRequest.ContentLength 值加倍,我仍然会遇到相同的错误。

最佳答案

Content-Length 必须以字节为单位指定,而不是 char s

var json = Encoding.UTF8.GetString(ms.ToArray());
httpWebRequest.ContentLength = Encoding.UTF8.GetByteCount(json);

关于json - "Bytes to be written to the stream exceed the Content-Length bytes size specified"与 UTF8 编码的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15429911/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com