Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 991
Carlo Avatar asked Dec 09 '22 17:12

Carlo


1 Answers

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

var json = Encoding.UTF8.GetString(ms.ToArray());
httpWebRequest.ContentLength = Encoding.UTF8.GetByteCount(json);
like image 162
Esailija Avatar answered Dec 27 '22 05:12

Esailija