C # How can I get server error from URL?

We have a url and we need to check if the webpage is active. We tried the following code: WebResponse objResponse = null;

WebRequest objRequest = HttpWebRequest.Create(URL); objRequest.Method = "HEAD"; try { objResponse = objRequest.GetResponse(); objResponse.Close(); } catch (Exception ex) { } 

I gave an exception above the code if I could not get the answer, but it also works fine, even if we have a "server error" on this page? Any help getting a server error?

+4
source share
2 answers

The HttpResponse class has a StatusCode property that you can check. If it's 200, everything is fine.

You can change your code to this:

  HttpWebResponse objResponse = null; var objRequest = HttpWebRequest.Create("http://google.com"); objResponse = (HttpWebResponse) objRequest.GetResponse(); if(objResponse.StatusCode != HttpStatusCode.OK) { Console.WriteLine("It failed"); }else{ Console.WriteLine("It worked"); } 
+5
source

First, use the using statement in the answer - this way you will manage it no matter what happens.

Now, if a WebException , you can catch this and look at WebException.Response to find out the status code and any data sent:

 WebRequest request = WebRequest.Create(URL); request.Method = "HEAD"; try { using (WebResponse response = request.GetResponse()) { // Use data for success case } } catch (WebException ex) { HttpWebResponse errorResponse = (HttpWebResponse) ex.Response; HttpStatusCode status = errorResponse.StatusCode; // etc } 
+2
source

All Articles