Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
669 views
in Technique[技术] by (71.8m points)

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

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 to see if it is possible connect to the Uri) but I would like implemented with "HttpStatusCode.OK" instead.

  • Do you know a better approach?

Thanks.

public static bool IsReachableUri(string uriInput)
        {
            // Variable to Return
            bool testStatus;
            // Create a request for the URL.
            WebRequest request = WebRequest.Create(uriInput);
            request.Timeout = 15000; // 15 Sec

            WebResponse response;
            try
            {
                response = request.GetResponse();
                testStatus = true; // Uri does exist                 
                response.Close();
            }
            catch (Exception)
            {
                testStatus = false; // Uri does not exist
            }
            // Result
            return testStatus;
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...