Recently one of my colleagues came with a problem, where he wanted to check the validity of a url submitted by the user for some reporting tool that he was writing. Since I've had some experience with HttpWebRequest, I asked him to use it to get the response and then check the StatusCode returned, everything was hunky-dory till people started entering Urls for huge pdfs and doc files et al, since the UrlChecker would make a Http-Get call to the Url, it meant getting the entire document from the Url which was putting some unnecessary load on our server. Well, if you just need to check for the validity of a url (i.e. if it's alive or not) you can use Http-Head method to only return the header information. This is how I did it:
private bool IsValid(string url)
{
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.Method = "HEAD";
HttpWebResponse ws = null;
try
{
ws = (HttpWebResponse)wr.GetResponse();
switch (ws.StatusCode)
{
case HttpStatusCode.OK:
case HttpStatusCode.Accepted:
return true;
break;
}
}
catch (HttpException e)
{
if (ws != null)
{
switch (ws.StatusCode)
{
case HttpStatusCode.Forbidden:
case HttpStatusCode.NotFound:
return false;
}
}
}
finally
{
if (ws != null)
ws.Close();
}
//dummy return
return false;
}
No comments:
Post a Comment