当前位置:编程学习 > C#/ASP.NET >>

c# 下载网页源码 获取http状态码

 

c# 下载网页源码 获取http状态码

 HttpWebRequest hwr = (HttpWebRequest) WebRequest.Create("http://www.baidu.com");

            hwr.AllowAutoRedirect = false; //不允许重定向

            hwr.Timeout = 10000; //连接超时时间设置

            hwr.Method = "GET"; //协议:GET、HEAD、POST、PUT、DELETE、TRACE 或OPTIONS。

            try

            {

                HttpWebResponse hwrs = (HttpWebResponse)hwr.GetResponse();

                MessageBox.Show(((int)hwrs.StatusCode).ToString()); //获得http状态码 如:200但是404却捕捉不到

                Stream stream=hwrs.GetResponseStream();

                MessageBox.Show(hwrs.CharacterSet); //获取返回结果的字符编码

                StreamReader sr = new StreamReader(stream,Encoding.GetEncoding(hwrs.CharacterSet)); //注意读取的文字编码格式要和写入文件的文字编码格式相同

                StreamWriter sw = new StreamWriter("c:\\b.html",false,Encoding.GetEncoding(hwrs.CharacterSet)); //写入文字的编码格式和读取时候的编码格式一样

                sw.Write(sr.ReadToEnd());

                sw.Flush();

                sw.Close();

                sr.Close();

 

 

            }

            catch(Exception ex)

            {

                MessageBox.Show(ex.ToString());

            }

摘自Shine的圣天堂-〃敏〃

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,