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

后端 未结 2 1537
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:40

    There are three possible options

    • Fix the ContentLength as described in the answer from @rene

    • Don't set the ContentLength, the HttpWebRequest is buffering the data, and sets the ContentLength automatically

    • Set the SendChunked property to true, and don't set the ContentLength. The request is send chunk encoded to the webserver. (needs HTTP 1.1 and has to be supported by the webserver)

    Code:

    ...
    request.SendChunked = true;
    using (Stream writeStream = request.GetRequestStream())
    { ... }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题