4

在将 JSON 对象发送到 Mandrill API 时,我遇到了编码问题。在使用 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 值加倍,我仍然会得到同样的错误。

4

1 回答 1

14

Content-Length必须以字节指定,而不是chars

var json = Encoding.UTF8.GetString(ms.ToArray());
httpWebRequest.ContentLength = Encoding.UTF8.GetByteCount(json);
于 2013-03-15T11:52:50.617 回答