PDA

View Full Version : C# Checking for valid URL


ninjatruck
11-07-2009, 08:03 PM
I am trying to write a web app that will check to see if a given URL is valid. This is the code i have so far:


WebRequest wr = WebRequest.Create(url);
wr.Method = WebRequestMethods.Http.Head;
try
{
using (HttpWebResponse response = (HttpWebResponse)wr.GetResponse())
{
Label1.Text = (response.StatusCode.ToString());
}
}

catch (Exception)
{
Label1.Text = ("Invalid URL");

}


It works for checking if http://www.google.com, Label1 reads "OK" after, and it also works with a non existent page, such as http://www.google.com/notapage, but I'm trying to check to see if, for example, "http://www.amazon.com/exec/obidos/ASIN/B000GELXHY" is a valid URL, and after the code is executed, Label1 reads "Invalid URL", even though this is a valid URL.

I am new to C#, so I may be using the wrong class for what I'm trying to do. Any help would be greatly appreciated.

P.S. I don't know if it's relevant, but the code is being executed upon a button click.
P.S.S. replace "url" above with whatever url i am currently testing

Freon22
11-08-2009, 02:52 AM
Ok I redid your code a little and it shows good url where it is good and bad url where they return an error 404. I made it a little simpler then yours hope this help. btw could you please post back if this help or even if it doesn't. Thanks


using System.Net;


protected void btnTestURL_Click(object sender, EventArgs e)
{
try
{
string url = TextBox1.Text;
if (url != "")
{
WebRequest Irequest = WebRequest.Create(url);
WebResponse Iresponse = Irequest.GetResponse();
if (Iresponse != null)
{
Label1.Text = "This is a good URL.";
}
}
}
catch (Exception ex)
{
Label1.Text = "This is a bad URL it returns an ERROR 404 >>>>>>>> " + ex.ToString();
}
}