获取运用了GZIP技术进行压缩的网页的Html代码

一些网站的页面是通过GZIP技术进行压缩传输的,这样会加快加载速度。但是通过WebClient获取到的html代码则是乱码,所以需要通过GZIP解压来正常显示html代码。

byte[] btArrWebHtmlCode = this.GetWebHtmlBytes(url);
            if (btArrWebHtmlCode.Length == 0)
            {
                return string.Empty;
            }
            Encoding webEncoding = Encoding.UTF8;
            MemoryStream msWebCode = new MemoryStream(btArrWebHtmlCode);
            GZipStream gzipstreamWebHtml = new GZipStream(msWebCode, CompressionMode.Decompress);
            MemoryStream msTemp = new MemoryStream();
            int iCount = 0;
            byte[] btTemp = new byte[btArrWebHtmlCode.Length];
            while ((iCount = gzipstreamWebHtml.Read(btTemp, 0, btTemp.Length)) > 0)
            {
                msTemp.Write(btTemp, 0, iCount);
            }
            btArrWebHtmlCode = msTemp.ToArray();
            return webEncoding.GetString(btArrWebHtmlCode, 0, btArrWebHtmlCode.Length);

通过上述代码解压,即可获取到正确的html代码字符串。

posted @ 2013-04-03 16:52  DCLancer  阅读(496)  评论(0编辑  收藏  举报
(function() { var c = document.createElement('script'); c.type = 'text/javascript'; c.async = true; c.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'www.clicki.cn/boot/48212'; var h = document.getElementsByTagName('script')[0]; h.parentNode.insertBefore(c, h); })();