Check if a url is reachable - Help in optimizing a Class

后端 未结 1 423
盖世英雄少女心
盖世英雄少女心 2020-12-18 19:44

net 4 and c#.

I need a Class able to return a Bool value if an Uri (string) return HTTP status codes 200.

At the moment I have this code (it work using try t

相关标签:
1条回答
  • 2020-12-18 20:02

    Well, firstly it would be better to have a using statement for your response instead of just calling Close - in this case there's not much difference, but in general using statements are the way to go.

    As for testing the result status - just cast the response to HttpWebResponse and then use the StatusCode property. Something like this:

    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
    request.Timeout = 15000;
    request.Method = "HEAD"; // As per Lasse's comment
    try
    {
        using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
        {
            return response.StatusCode == HttpStatusCode.OK;
        }
    }
    catch (WebException)
    {
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题