如何检查一个网站是否在C#中在线?
您已使用System.Net.NetworkInformation.Ping
见下文。
var ping = new System.Net.NetworkInformation.Ping();
var result = ping.Send("www.google.com");
if (result.Status != System.Net.NetworkInformation.IPStatus.Success)
return;
我能想到的最简单的方法是一样的东西:
WebClient webClient = new WebClient();
byte[] result = webClient.DownloadData("http://site.com/x.html");
如果网站不在线DownloadData会抛出异常。
可能有类似的方法来ping网站,但除非您每秒检查多次,否则这种差异不太可能引人注目。
您不应该下载整个页面来验证该网站是否已启动 – BrokenGlass
在运行到错误503后,webclient对我更好,而不是httpwebrequest,httpwebrequest在webclient再次运行时继续抛出503。 – bert
Ping只告诉你端口是活动的,它并不告诉你它是否真的是一个Web服务。
我的建议是针对URL
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("your url");
request.AllowAutoRedirect = false; // find out if this site is up and don't follow a redirector
request.Method = "HEAD";
try {
response = request.GetResponse();
// do something with response.Headers to find out information about the request
} catch (WebException wex)
{
//set flag if there was a timeout or some other issues
}
这执行HTTP HEAD请求不会实际获取的HTML页面,但它会帮助你找到最低的,你需要知道的。对不起,如果代码不编译,这只是我的头顶。
完美。顺便说一句,对于那些关心的人来说,实际上有一个“HEAD”的常量。 System.Net.WebRequestMethods.Http.Head。 –
小注记Digicoder的代码和Ping方法的完整的例子:
private bool Ping(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Timeout = 3000;
request.AllowAutoRedirect = false; // find out if this site is up and don't follow a redirector
request.Method = "HEAD";
using (var response = request.GetResponse())
{
return true;
}
}
catch
{
return false;
}
}
if (!NetworkInterface.GetIsNetworkAvailable())
{
// Network does not available.
return;
}
Uri uri = new Uri("http://stackoverflow.com/any-uri");
Ping ping = new Ping();
PingReply pingReply = ping.Send(uri.Host);
if (pingReply.Status != IPStatus.Success)
{
// Website does not available.
return;
}
对[平类]同步和异步的例子(http://msdn.microsoft.com/en- us/library/system.net.networkinformation.ping.aspx)MSDN上的页面。 – drew010
+1。学到了新东西:D –
您也可以使用WebClient类并请求资源或URL。 Ping不一定意味着网站在线,除非你只是想检查服务器是否启动。 – lahsrah