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.
The Content-Length
must be specified in bytes, not char
s
var json = Encoding.UTF8.GetString(ms.ToArray());
httpWebRequest.ContentLength = Encoding.UTF8.GetByteCount(json);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With