Error (HttpWebRequest): Bytes to be written to the stream exceed the Content-Length bytes size specified

后端 未结 2 1536
Happy的楠姐
Happy的楠姐 2020-12-18 22:57

I can\'t seem to figure out why I keep getting the following error:

Bytes to be written to the stream exceed the Content-Length bytes size specified.
         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-18 23:53

    The Encoded byte array from your InnerXml might be longer as some characters in an UTF8 encoding take up 2 or 3 bytes for a single character.

    Change your code as follows:

        using (Stream writeStream = request.GetRequestStream())
        {
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] bytes = encoding.GetBytes(doc.InnerXml);
            request.ContentLength = bytes.Length;
            writeStream.Write(bytes, 0, bytes.Length);
        }
    

    To show exactly what is going on, try this in LINQPad:

    var s = "é";
    s.Length.Dump("string length");
    Encoding.UTF8.GetBytes(s).Length.Dump("array length");
    

    This will output:

     string length: 1 
     array length:  2 
    

    and now use an e without the apostrophe:

    var s = "e";
    s.Length.Dump("string length");
    Encoding.UTF8.GetBytes(s).Length.Dump("array length");
    

    which will output:

    string length: 1 
    array length:  1 
    

    So remember: string length and the number of bytes needed for a specific encoding might differ.

提交回复
热议问题