日期:2008-09-11  浏览次数:20545 次


就是说我想监控一个网站,我想用程序写:隔一断时间就访问一下,看它是否好使!

WebRequest myWebRequest=WebRequest.Create("一个无效链接的地址");
myWebRequest.Timeout=5000;
try
{
WebResponse myWebResponse=myWebRequest.GetResponse();
Stream resStream = myWebResponse.GetResponseStream();
StreamReader sr = new StreamReader(resStream, System.Text.Encoding.Default);
this.Label1.Text = sr.ReadToEnd();
resStream.Close();
sr.Close();
}
catch(System.Net.WebException xx)
{
this.Label1.Text=xx.Message;
}

如果label标签显示:无效的地址404错误说明链接无效
(如果有效的话label标签显示网页源代码)

==================================================================================

WebRequest myWebRequest=WebRequest.Create(@"要试验的地址");
myWebRequest.Timeout=-1;
try
{
WebResponse webResponse=webRequest.GetResponse();
Stream webStream = webResponse.GetResponseStream();
webStream.Close();

}
catch(System.Net.WebException e)
{
  //如果是得到了Web服务器的响应,但是错误响应,则输出错误类型和其描述
   if(e.Status == WebExceptionStatus.ProtocolError)
   {
    Console.WriteLine("Status Code 222: {0}", ((HttpWebResponse)e.Response).StatusCode);
    Console.WriteLine("Status Description 333: {0}", ((HttpWebResponse)e.Response).StatusDescription);
    //Console.WriteLine(e.Message+"TimeOUt");
   }

   //如果是Web服务器超时而没有响应,则输出超时信息
   //超时值在上面的.wReq.Timeout属性里设置
   if(e.Status == WebExceptionStatus.Timeout)
   {
    Console.WriteLine(e.Message+"TimeOUt");
   }
//添加代码说明此链接不能访问
}