阅读来自 HttpWebResponse 的完整响应

Reading full response from HttpWebResponse

我需要从 API 那里得到完整的回应,但我总是得到 65536 字节 内容长度显示 176579。 我试着连续阅读,但仍然得到 65536 字节。 与邮递员一起,我得到了完整的答案 那么从 WebResponse 读取的正确方法是什么? 这是我的代码:

string json = Request.ToJson(data);
string method = "POST";
string ContentType = "application/json; charset=utf-8";

HttpWebRequest client = (HttpWebRequest)WebRequest.Create(uri);
client.Method = method;
client.KeepAlive = true;
client.Timeout = 3000;
client.ReadWriteTimeout = 50000;
client.AllowWriteStreamBuffering = true;
client.ContentType = ContentType;                

using (var streamWriter = new StreamWriter(client.GetRequestStream()))
{
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

var errorResponse = client.GetResponse();
byte[] dt = ReadFully(errorResponse.GetResponseStream(), errorResponse.ContentLength);
var str = System.Text.Encoding.Default.GetString(dt);

这里是 ReadFully 方法(从另一个答案复制而来):

private byte[] ReadFully(Stream stream, long initialLength)
{
    // If we've been passed an unhelpful initial length, just
    // use 32K.
    byte[] bytes;
    using (MemoryStream buffer = new MemoryStream((int)initialLength))
    {
        byte[] chunk = new byte[initialLength];
        int bytesRead;
        while ((bytesRead = stream.Read(chunk, 0, chunk.Length)) > 0)
        {
            buffer.Write(chunk, 0, bytesRead);
        }

        bytes = buffer.ToArray();
    }

    return bytes;
}

正如评论中所暗示的那样,errorResponse 变量似乎取自 WebException.Response。读取底层流时有 65536 字节的限制。您可以通过设置以下静态 属性:

来增加此限制
HttpWebRequest.DefaultMaximumErrorResponseLength = some reasonably large number