现在管理的网站(主要是一些小网站)不下几十个每天早上一来要浏览一遍,看一下这些网站是否能正常的访问.这是一项枯燥又不得不做的事,后来想用程序来实现这一工作,跳离重复的去验证工作.
首先选用的是HttpWebRequest HttpWebResponse 来读返回状态码;后来发现这是徒劳的一些不能访问的网站被劫持到“铁通”一个固定ip的网站页面下。又换用IPHostEntry hostentry = Dns.Resolve(url); IPEndPoint ipendpoint= new IPEndPoint(hostentry.AddressList[0],0);来找ip 结果同样被被劫持到“铁通”一个固定ip(可能是我对HttpWebRequest了解不深)。
不得不选用WebBrowser 这个比较“耗资源”的控件来实现了
一.首先建一个form 加入一个 linklabel 一个button 一个webbrowser 控件就齐了
二. 为了记录时间加入了一个private Stopwatch sw = new Stopwatch(); //建立一个记时函数
using System.Diagnostics;
using System.Collections.Specialized;
StringCollection sc = new StringCollection();//为了记录出错信息
三.将所有的网址放入一个数组
private string[] UrlAddress()
{ string[] urladdress ={
"http://www.xxx.com/,,网站标题x", //用两个逗号做截断
"http://www.yyy.com/,,网站标题y"};
return urladdress;
}
四.创建按钮响应事件
private void buttonCheck_Click(object sender, EventArgs e)
{
sw.Start();
string[] url = UrlAddress();
array = null;
this.webBrowserResult.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);//加载完成后的委托事件
for (int i = 0; i < url.Length; i++)
{
this.linkLabelUrlAddress.Text = url[i];
this.linkLabelUrlAddress.Refresh();
loading = true;
array = url[i].Split(new string[] { ".." }, StringSplitOptions.None); //分割字符串
this.webBrowserResult.Navigate(array[0]);
while (loading)
{
Application.DoEvents();
}
// this.webBrowserResult.Show();
//System.Threading.Thread.Sleep(3000);
// this.webBrowserResult.Hide();
}
for (int i = 0; i < sc.Count; i++)
{
this.textBoxUrl.AppendText(sc[i]);
}
this.webBrowserResult.Visible = false;
this.textBoxUrl.Visible = true;
this.textBoxUrl.Refresh();
MessageBox.Show("查询用时" + sw.Elapsed.ToString()); //计时显示并结束
sw.Stop();
}
五. WebBrowser 控件完成加载后的事件
private void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if(this.webBrowserResult.ReadyState==WebBrowserReadyState.Complete )
{
loading = false;
if (this.webBrowserResult.Document != null)
{
string title = this.webBrowserResult.Document.Title.ToString();
string url = this.webBrowserResult.Document.Url.ToString();
if (title.Equals("中国铁通提醒您! 您输入的域名无法访问!"))
{
sc.Add(url+"被铁通截获无法访问!!!");
this.webBrowserResult.Stop();
}
else if(title.IndexOf(array[1])<0)
{
sc.Add(url + "访问出现异常 ----异常提示" + title+"!!!");
this.webBrowserResult.Stop();
}
}
}
}
这个小程序可以用但是不是太理想几十个网站大概要两三分钟才可以完成判断。也没用多线程(主要是不知道怎么用)那里要改进的希望广大网友给我留言
[@more@]来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/13380151/viewspace-1024233/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/13380151/viewspace-1024233/