using System;
using System.IO.Compression;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Headers["Accept-Encoding"].ToLower().IndexOf("gzip") != -1)
{
Response.Filter = new GZipStream(Response.Filter, CompressionMode.Compress);
Response.AppendHeader("Content-Encoding", "gzip");//不设置浏览器显示为乱码
}
Response.WriteFile(Server.MapPath("book.txt"));
}
}
启用gzip压缩前后对比:
大多数浏览器自带了gzip解压功能,经gzip压缩后的页面不需做格外的操作就能正常显示了。但url若做为接口使用,在应用程序中获取返回内容时,则需手工进行解压,示例代码:
using System;
using System.IO;
using System.IO.Compression;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//请求
WebRequest Request = WebRequest.Create("http://localhost:2440/Default.aspx");
Request.ContentType = "application/x-www-form-urlencoded";
Request.Method = "GET";
//响应
WebResponse Response = Request.GetResponse();
Stream stream = Response.GetResponseStream();
//解压
byte[] buffer = new byte[100];
int length = 0;
using (GZipStream gz = new GZipStream(stream, CompressionMode.Decompress))
{
using (MemoryStream msTemp = new MemoryStream())
{
while ((length = gz.Read(buffer, 0, buffer.Length)) != 0)
{
msTemp.Write(buffer, 0, length);
}
Console.WriteLine(System.Text.Encoding.UTF8.GetString(msTemp.ToArray()));
}
}
Console.ReadKey();
}
}
}
CIO之家 www.ciozj.com 公众号:imciow