Jieqin
Jieqin

Reputation: 588

How To Check Whether A URL Is Valid?

I want to be able to check whether a specified URL is valid [Preferably both Active and Well Formed],

eg

//invalid
http://fdsafsd.com/
//valid
http://google.com/

Is it possible? I was using the codes specified on other posts in stackoverflow but they all don't seem to work. This is one of the examples.

private bool checkWebsite(string url){
    WebRequest webRequest = WebRequest.Create(url);
    WebResponse webResponse;
    try{
        //System.Net.WebRequest does not contain a definition for GetResponse();
        webResponse = webRequest.GetResponse();
    }
    catch
        return false;
    return true;
}

Any help is appreciated. Thank you in advance.

Upvotes: 1

Views: 969

Answers (2)

aloisdg
aloisdg

Reputation: 23521

Answer with a HttpClient ( You should add using System.Net.Http;) :

    private async Task<bool> IsURLAvailable(Uri url)
    {
        var httpClient = new HttpClient();

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, url);
        HttpResponseMessage response = await httpClient.SendAsync(request);
        try
        {
            if (response.StatusCode == HttpStatusCode.OK)
                return true;
        }
        catch (WebException e)
        {
            Debug.WriteLine(e.Message);
        }
        return false;
    }

Upvotes: 0

Shulhi Sapli
Shulhi Sapli

Reputation: 2476

This should work for you. Not the most elegance code though.

static void Main(string[] args)
{
    var uriName = "http://www.google.com";
    Uri uriResult;

    bool isUriValid = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;

    if (isUriValid)
    {
        var webRequest = HttpWebRequest.Create(uriResult);
        // Only request the headers, not the whole content
        webRequest.Method = "HEAD";
        try
        {
            // Exception is thrown if 404
            var response = webRequest.GetResponse() as HttpWebResponse;
            // Check if status return is 200 OK, then active. You might want to check the HttpStatusCode for others
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Console.WriteLine(((int)response.StatusCode).ToString());
            }
        }
        catch (WebException e)
        {
            Console.WriteLine(e.Message);
        }  
    }
    else
    {
        Console.WriteLine("Url is not valid");
    }

    Console.Read();
}

Upvotes: 1

Related Questions