这篇文章上次修改于 631 天前,可能其部分内容已经发生变化,如有疑问可询问作者。
该方法能获取使用 gzip 或者 deflate 压缩过的内容。
public static string GetResponseBody(HttpWebResponse response)
{
    string responseBody = string.Empty;

    if (response.ContentEncoding != null && response.ContentEncoding.ToLower().Contains("gzip"))
    {
        using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
        {
            using (StreamReader reader = new StreamReader(stream))
            {
                responseBody = reader.ReadToEnd();
            }
        }
    }
    else if (response.ContentEncoding != null && response.ContentEncoding.ToLower().Contains("deflate"))
    {
        using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress))
        {
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                responseBody = reader.ReadToEnd();
            }
        }
    }
    else
    {
        using (Stream stream = response.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                responseBody = reader.ReadToEnd();
            }
        }
    }
    return responseBody;
}