Reading “chunked” response with HttpWebResponse

前端 未结 4 1209
谎友^
谎友^ 2020-12-16 18:47

I\'m having trouble reading a \"chunked\" response when using a StreamReader to read the stream returned by GetResponseStream() of a HttpWebResponse:

// resp         


        
4条回答
  •  抹茶落季
    2020-12-16 18:58

    After trying a lot of snippets from StackOverflow and Google, ultimately I found this to work the best (assuming you know the data a UTF8 string, if not, you can just keep the byte array and process appropriately):

    byte[] data;
    var responseStream = response.GetResponseStream();
    var reader = new StreamReader(responseStream, Encoding.UTF8);
    data = Encoding.UTF8.GetBytes(reader.ReadToEnd());
    return Encoding.Default.GetString(data.ToArray());
    

    I found other variations work most of the time, but occasionally truncate the data. I got this snippet from:

    https://social.msdn.microsoft.com/Forums/en-US/4f28d99d-9794-434b-8b78-7f9245c099c4/problems-with-httpwebrequest-and-transferencoding-chunked?forum=ncl

提交回复
热议问题