"Bytes to be written to the stream exceed the Content-Length bytes size specified" with UTF8 encoded json

Carlo picture Carlo · Mar 15, 2013 · Viewed 9.6k times · Source

I'm facing encoding problems while sending a JSON object to Mandrill API. While writing to a streamwriter with UTF8 encoding the following exception is thrown:

"Bytes to be written to the stream exceed the Content-Length bytes size specified." and right after: "Cannot close stream until all bytes are written."

This is the portion of code used to send the JSON object:

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

It seems to me that this error is related to byte length in UTF8, but even if I double the httpWebRequest.ContentLength value I still get the same error.

Answer

Esailija picture Esailija · Mar 15, 2013

The Content-Length must be specified in bytes, not chars

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