饼干是这样压缩的——GZIP & Deflate (.NET版)

[ 2008-1-28 16:15:00 | By: 99love ]

本来想直接回在Fanbin的贴子后,但是因为他的标签是PHP的,所以就开了新贴。
Fanbin的原贴在http://bbs.blueidea.com/thread-2827128-1-1.html

.NET也可以用GZIP,用法比PHP要简单,不过压缩程度没有那么高,只能大概压缩到原先页面的63%左右。

这是Fanbin的代码片断,其压缩的参数有一个9,.NET中我没有找到相应的,所以压缩率就是固定的了:



 


$content = gzencode($content." \n//此页已压缩",9); 为准备压缩的内容贴上“//此页已压缩”的注释标签,然后用zlib提供的gzencode()函数执行级别为9的压缩,这个参数值范围是0-9,0表示无压缩,9表示最大压缩,当然压缩程度越高越费CPU。


.NET的压缩页面和Fanbin的思路差不多,先检测浏览器是否支持压缩页面,如果支持,才向浏览器输出压缩页面。

下面两个函数是App_Code中GZIP类的函数。

检测浏览器是否支持压缩的函数:






public static bool IsGZipSupported()


    {


        string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];//检测headers中的Accept-Encoding


        if (!string.IsNullOrEmpty(AcceptEncoding) && (AcceptEncoding.Contains("gzip") || AcceptEncoding.Contains("deflate")))//如果Accept-Encoding含有gzipdeflate,表示浏览器支持这种压缩。


            return true;


        return false;


    }



使用压缩页面的函数:




   

public static void GZipEncodePage()


    {


        if (IsGZipSupported())//如果支持压缩


        {


            HttpResponse Response = HttpContext.Current.Response;


            string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];


            if (AcceptEncoding.Contains("gzip"))//如果支持gzip,就使用gzip的压缩方式


            {


                Response.Filter = new System.IO.Compression.GZipStream(Response.Filter,


                                          System.IO.Compression.CompressionMode.Compress);//只需要把HttpResponse.Filter变成GZipStream就行了。


                Response.AppendHeader("Content-Encoding", "gzip");//添加gzip到浏览器header


            }


            else//采用defalte的压缩方式,另一种内置的压缩方式。


            {


                Response.Filter = new System.IO.Compression.DeflateStream(Response.Filter,


                                          System.IO.Compression.CompressionMode.Compress);//同样原理


                Response.AppendHeader("Content-Encoding", "deflate");//添加deflate到浏览器header


            }


        }


}



函数就是这两个了,只需要在页面的Page_Load中调用GZipEncodePage就行了。




   

protected void Page_Load(object sender, EventArgs e)


    {


        GZIP.GZipEncodePage();//我上面说过这是GZIP类中的函数的。


    }



压缩效果:
1、这是一个未经压缩的页面。Content-Length: 5270。




HTTP/1.1 200 OK
Server: ASP.NET Development Server/8.0.0.0
Date: Mon, 28 Jan 2008 07:53:25 GMT
X-AspNet-Version: 2.0.50727
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 5270
Connection: Close


2、这是压缩后的同一页面。Content-Length: 3310



 


HTTP/1.1 200 OK
Server: ASP.NET Development Server/8.0.0.0
Date: Mon, 28 Jan 2008 07:52:59 GMT
X-AspNet-Version: 2.0.50727
Content-Encoding: gzip
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 3310
Connection: Close


可以看出,压缩率为3310/5270=62.81%,用Fanbin的话说:“这样用户浏览的时候就会感觉很爽很愉快!”。

发表评论:

    密码:
    主页:
    标题:
    页面数据正在载入...
bxna 京ICP备05002321号