代码如下,大家慢慢琢磨下:
HttpWebRequest hwr = (HttpWebRequest) WebRequest.Create("http://www.jb200.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());
}