How to check if a resource is available on server

Sometimes it can be useful to know if a resource is available before trying to load it from another server.

See code below:


/// <summary>
/// This method will check a url to see that it does not return server or protocol errors
/// </summary>
/// <param name="url">The path to check</param>
/// <returns></returns>
public static bool UrlIsValid(string url)
{
try
{
HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
request.Timeout = 5000; //set the timeout to 5 seconds to keep the user from waiting too long for the page to load
request.Method = "HEAD"; //Get only the header information -- no need to download any content

int statusCode = Null.NullInteger; // NullInteger is -1
using (var response = request.GetResponse() as HttpWebResponse)
{
statusCode = Convert.ToInt32(response.StatusCode);
}

// Check Status Code
if (statusCode >= 100 && statusCode < 400) //Good requests
return true;
else if (statusCode >= 500 && statusCode <= 510) //Server Errors
return false;
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError) //400 errors
{
return false;
}
else
{
_logger.Error(String.Format("Unhandled status [{0}] returned for url: {1}", ex.Status, url), ex);
}
}
catch (Exception ex)
{
_logger.Error(String.Format("Could not test url {0}.", url), ex);
}
return false;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s