zoukankan      html  css  js  c++  java
  • HttpWebRequest、HttpWebResponse获取网页

    1,通过HttpWebRequest、HttpWebResponse获取一个流

                    request =  (HttpWebRequest)System.Net.WebRequest.Create(this._url);
                    HttpWebResponse response =  (HttpWebResponse)request.GetResponse();
                    Stream  reciveStream =   response.GetResponseStream();

    2,读取流成字符串

    方法1:利用Stream的Read方法

     byte[] byteData = new byte[response.ContentLength];
                    int count = byteData.Length, offset = 0;
                    while (count > 0)
                    {
                        int n = reciveStream.Read(byteData, offset, count);
                        if (n == 0)
                        {
                            break;
                        }
                        offset += n;
                        count -= n;
                    }
    
                    string strHtml =  System.Text.Encoding.GetEncoding("utf-8").GetString(byteData);
                    lstURL.Add(strHtml);
                    response.Close();

    方法1中的response.ContentLength可能为-1(和服务器的压缩有关),造成数组初始化失败。

    网上方法:添加 request.Headers.Set("Accept-Encoding", "identity"); 强制服务器不压缩,但是我测试的时候总是超时,所以该方法可靠性不定。

    建议不要用方法1,用下面的方法2。

    方法2:利用StreamReader

    using (StreamReader reader = new StreamReader(reciveStream, System.Text.Encoding.UTF8))
                    {
                        string strHtml = reader.ReadToEnd();
    
                        lstURL.Add(strHtml);
                    }
                    response.Close();

    注意点:

    1,要关闭流。(选一个就可以了)

    response.Close() 或 reciveStream.Close()

    2,注意编码。

    StreamReader默认使用utf-8。
    不管是使用stream,还是streamReader,都建议根据具体网页内容,指定编码,不然会出现乱码。
  • 相关阅读:
    centos6.5安装mysql5.7.20
    redis错误总结
    批量杀死MySQL连接的四种方法详解
    VMware虚拟机宿主机与虚拟机通讯慢解决方法
    linux下ssh/scp无密钥登陆方法
    天兔3.8安装 centos7
    《TensorFlow+Keras自然语言处理实战》已出版
    几本技术图书资源下载
    2020年上半年新书
    《Neo4j 图数据库扩展指南:APOC和ALGO》
  • 原文地址:https://www.cnblogs.com/xiashengwang/p/6889403.html
Copyright © 2011-2022 走看看