HttpWebRequest开启gzip压缩
2012-11-06 17:45
399 查看
在用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;
}
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;
}
相关文章推荐
- 【转载】HttpWebRequest开启gzip压缩简介
- HttpWebRequest开启gzip压缩
- 如何用HttpWebRequest下载gzip, deflate压缩的页面
- 如何用HttpWebRequest下载gzip, deflate压缩的页面
- 利用HttpWebRequest获取网页内容,由于Gzip压缩导致乱码的情况
- 如何用HttpWebRequest下载gzip, deflate压缩的页面
- 如何用HttpWebRequest下载gzip, deflate压缩的页面
- http配置如何开启gzip网页压缩
- [转]HttpWebRequest提高效率之连接数,代理,自动跳转,gzip请求等设置有关问题
- 使用ASIHTTPRequest的ASIDataCompressor与ASIDataDecompressor进行gzip压缩与解压缩,出现的问题
- httpwebrequest 请求压缩,接受压缩的字符流请求
- apache2.0x 开启gzip压缩和http缓存的配置方法
- HttpWebRequest 发送请求及开启监听
- ASIHTTPRequest中数据压缩问题与gzip
- C# 利用HttpWebRequest模拟登陆获取数据设置Accept-Encoding为gzip,deflate后返回的网页是乱码处理
- apache2.0x 开启gzip压缩和http缓存的配置方法
- Web服务器之Http压缩(GZip)
- [置顶] web服务交互中HTTP数据内容GZIP,ZLIB格式压缩与解压缩封装(共享)
- HttpClient、Tornado服务器开启gzip压缩功能
- ASIHTTPRequest中数据压缩问题与gzip