Get the HTTP status code from a URL
Yesterday, I wrote about the Ping class for checking network availability on remote machines. Then I started thinking about checking the availability of web servers. Even if a remote server is available over the network, the web server instance might not response to requests so we need another method to check if it’s responding correctly.
What we really want is not a Boolean value telling us if the web server is responding or not. The best way is to get the HTTP status code so we can act appropriately. The status code for a properly working web server is 200 and 404 if there is no reply. There are a lot of other codes that we can act differently upon as we please. Here’s a list of possible status codes.
This static method returns a System.Net.HttpStatusCode enumeration value based on the specified URL.
private static HttpStatusCode HttpStatus(string url)
{
HttpWebRequest request
= (HttpWebRequest)HttpWebRequest.Create(url);
try
{
using (HttpWebResponse response
= (HttpWebResponse)request.GetResponse())
{
return response.StatusCode;
}
}
catch (System.Net.WebException)
{
return HttpStatusCode.NotFound;
}
}
You can use it to write the status code to the response stream like this:
Response.Write((int)HttpStatus("http://www.google.com"));
By using this simple method it is very easy to build your own web server checking tool. If you want to run multiple URL checks from ASP.NET, it would be a good idea to use ASP.NET 2.0’s possibility for asynchronous processing for improved performance in situations where you are creating web requests.
Comments
Comments are closed