zoukankan      html  css  js  c++  java
  • c# 获取网页源代码(可解决某些页面乱码的问题)

      private string GetHtmlCode(string url)
             {
                 string htmlCode;
                 HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                 webRequest.Timeout = 30000;
                 webRequest.Method = "GET";
                 webRequest.UserAgent = "Mozilla/4.0";
                 webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
                 HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse();
                  if (webResponse.ContentEncoding.ToLower() == "gzip")//如果使用了GZip则先解压
                  {
                      using (System.IO.Stream streamReceive = webResponse.GetResponseStream())
                      {
                          using (var zipStream =
                              new System.IO.Compression.GZipStream(streamReceive, System.IO.Compression.CompressionMode.Decompress))
                          {
                              using (StreamReader sr = new System.IO.StreamReader(zipStream, Encoding.Default))
                             {
                                 htmlCode = sr.ReadToEnd();
                             }
                         }
                     }
                 }
                 else
                 {
                     using (System.IO.Stream streamReceive = webResponse.GetResponseStream())
                     {
                         using (System.IO.StreamReader sr = new System.IO.StreamReader(streamReceive, Encoding.Default))
                         {
                             htmlCode = sr.ReadToEnd();
                        }
                     }
                 }
     
                 return htmlCode;
            }
  • 相关阅读:
    【阿里的感悟】质量该如何做? .(转载)
    java linux 配置环境
    Spring Bean属性绑定Bean返回值
    Spring BeanNameAutoProxyCreator 与 ProxyFactoryBean
    Spring Aop之(二)Aop 切面声明和通知
    Ubuntu开机自动启动Script
    转战博客园!
    linux 系统管理11 ——系统安全及应用
    linux awk
    Rsync数据同步工具
  • 原文地址:https://www.cnblogs.com/8765h/p/2373630.html
Copyright © 2011-2022 走看看