This post has been in the works for awhile. I wrote this code a couple months ago and have been meaning to post it, but it got buried and I almost forgot about it. Anyway, this is a small bit of code I wrote as part of a failover mechanism for a web service client I was writing at the time.
Basically, this code implements what I call an HTTP “ping“ - it checks to see if the given URL will answer. Note that this is different from a normal ping command from the command line. That type of ping only checks to see if the box is up and on the network. This code checks to see what kind of HTTP response code will be sent back from the server, which will allow you to take appropriate action. For instance, in my web service client, if I got an HTTP response code other than OK (i.e. the HTTP 200 status code), I had to perform a retry.
To investigate the response code, you need to check the HttpStatusCode enumeration that gets populated on the HttpWebResponse object. Lots of useful information there.
Also, be sure to close the HttpWebResponse object. When I first wrote this I forgot to close it and kept getting weird results on successive calls.
Here's the code. Enjoy.
using System.Net;
public static void DoHttpPing()
{
HttpWebRequest httpReq;
HttpWebResponse httpRsp;
httpReq = (HttpWebRequest)WebRequest.Create("http://www.google.com/");
httpRsp = (HttpWebResponse)httpReq.GetResponse();
httpRsp.Close();
if (httpRsp.StatusCode == HttpStatusCode.OK)
{
// do something
}
else
{
// do something else
}
}
Print | posted on Sunday, September 26, 2004 12:46 AM