zoukankan      html  css  js  c++  java
  • WebRequest 获取网页乱码

    问题:在用WebRequest获取网页源码时得到的源码是乱码。

    原因:1,编码不对

    解决办法:设置对应编码

    WebRequest request = WebRequest.Create(Url);
    WebResponse response = await request.GetResponseAsync();

    Stream stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(coding));//这里的coding是页面的编码,可以用Ie右键查看编码。
    Result = reader.ReadToEnd();

    reader.Dispose();
    reader.Dispose();

    2,页面进行压缩了

    看看html的head,ContentEncoding是否是gzip如果是的话需要解压。//下面的代码是在winrt下的

          WebRequest request = WebRequest.Create(Url);
                    WebResponse response = await request.GetResponseAsync();
                    Debug.WriteLine(((HttpWebResponse)response).StatusDescription);
                    if (response.Headers.AllKeys.Contains("Content-Encoding") && response.Headers["Content-Encoding"].ToLower() == "gzip")//如果使用了GZip则先解压
                    {
                        using (System.IO.Stream streamReceive = response.GetResponseStream())
                        {
                            using (var zipStream =
                                new System.IO.Compression.GZipStream(streamReceive, System.IO.Compression.CompressionMode.Decompress))
                            {
                                using (StreamReader sr = new System.IO.StreamReader(zipStream, Encoding.GetEncoding(coding)))
                                {
                                    Result = sr.ReadToEnd();
                                }
                            }
                        }
                    }

  • 相关阅读:
    微软ASP.NET网站部署指南(4):配置项目属性
    iOS 设计模式之抽象工厂
    How can I move a MySQL database from one server to another?
    CentOS 7 上安装vim(默认未安装)
    How to resize slide dimensions without resizing any objects on the slide?
    CentOS 7.3 上安装docker
    美国留学访学(访问学者)必备信用卡
    西安理工大学税务登记证、银行账号信息
    Oracle联合多个子查询(inner join)
    linux tail
  • 原文地址:https://www.cnblogs.com/wangjinming/p/3835366.html
Copyright © 2011-2022 走看看