1 HttpWebRequest hwr = (HttpWebRequest) WebRequest.Create("http://www.baidu.com"); 2 3 hwr.AllowAutoRedirect = false; //不允许重定向 4 5 hwr.Timeout = 10000; //连接超时时间设置 6 7 hwr.Method = "GET"; //协议:GET、HEAD、POST、PUT、DELETE、TRACE 或OPTIONS。 8 9 try 10 11 { 12 13 HttpWebResponse hwrs = (HttpWebResponse)hwr.GetResponse(); 14 15 MessageBox.Show(((int)hwrs.StatusCode).ToString()); //获得http状态码 如:200但是404却捕捉不到 16 17 Stream stream=hwrs.GetResponseStream(); 18 19 MessageBox.Show(hwrs.CharacterSet); //获取返回结果的字符编码 20 21 StreamReader sr = new StreamReader(stream,Encoding.GetEncoding(hwrs.CharacterSet)); //注意读取的文字编码格式要和写入文件的文字编码格式相同 22 23 StreamWriter sw = new StreamWriter("c:\\b.html",false,Encoding.GetEncoding(hwrs.CharacterSet)); //写入文字的编码格式和读取时候的编码格式一样 24 25 sw.Write(sr.ReadToEnd()); 26 27 sw.Flush(); 28 29 sw.Close(); 30 31 sr.Close(); 32 33 34 35 36 37 } 38 39 catch(Exception ex) 40 41 { 42 43 MessageBox.Show(ex.ToString()); 44 45 }