关闭

获取网页内容

242人阅读 评论(0) 收藏 举报
public string get_html(string url)
        {
            HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(url);     
            hwr.Timeout = 60000;                                                  //服务器超时时间
            /*
            WebProxy proxy = new WebProxy();                                      // 定義一個網關對象
            proxy.Address = new Uri("http://proxy.domain.com:3128");              // 網關服務器:端口
            proxy.Credentials = new NetworkCredential("f3210316", "6978233");      //用戶名,密碼
            hwr.UseDefaultCredentials = true;                                      //啟用網關認証
            hwr.Proxy = proxy;                                                      //設置網關
            */
            HttpWebResponse hwrs;
            try
            {
                hwrs = (HttpWebResponse)hwr.GetResponse();              //取得回應
            }
            catch
            {
                MessageBox.Show("无法连接!");
                return "error";
            }
            //判断HTTP响应状态
            if (hwrs.StatusCode != HttpStatusCode.OK)
            {
                MessageBox.Show("访问失败!");
                hwrs.Close();
                return "error";
            }
            else
            {
                Stream s = hwrs.GetResponseStream();                                  //得到回應的流對象
                StreamReader sr = new StreamReader(s,Encoding.Default);                  //以UTF-8編碼讀取流
                StringBuilder content = new StringBuilder();                          //
                while (sr.Peek() != -1)                                                  //每次讀取一行,直到
                {                                                                      //下一個字節沒有內容
                    content.Append(sr.ReadLine() + "/r/n");                              //返回為止
                }                                                                      //
                return content.ToString();
            }
            //输出所有的Header(当然包括服务器输出的Cookie)
            //for(int ii=0;ii<hwrs.Headers.Count;ii++)
            //{
            //MessageBox.Show(hwrs.Headers.GetKey(ii)+":"+res.Headers[ii]);
            //}
        }
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:18009次
    • 积分:417
    • 等级:
    • 排名:千里之外
    • 原创:22篇
    • 转载:9篇
    • 译文:0篇
    • 评论:0条
    文章分类