码迷,mamicode.com
首页 > Web开发 > 详细

【转载】HttpWebRequest开启gzip压缩简介

时间:2014-09-13 14:38:45      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   strong   数据   div   

在用HttpWebRequest对象时,一般我们都没有开启gzip压缩,如果服务端返回的数据比较大,这是我们需要开启gzip压缩,怎么开启呢?

1.给HttpWebRequest对象,添加如下Header:

request.Headers.Add("Accept-Encoding", "gzip");

2.对接收到的流进行解码:

private string GetResponseBody(HttpWebResponse response)
{
    string responseBody = string.Empty;
    if (response.ContentEncoding.ToLower().Contains("gzip"))            
  {
        using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
        {
            using (StreamReaderreader = new StreamReader(stream))
            {
                responseBody = reader.ReadToEnd();
            }
        }
    }
    else if (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;
}

转自:http://www.csharpwin.com/csharpspace/13345r5893.shtml

【转载】HttpWebRequest开启gzip压缩简介

标签:style   blog   http   color   io   ar   strong   数据   div   

原文地址:http://www.cnblogs.com/crazybottle/p/3969784.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!