一些网站的页面是通过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代码字符串。