Friday, April 29, 2011

WebRequest get page w/o exceptions?

I want to check the status of a page (404, moved, etc). How can i do it? ATM i am doing the below which only tells me if the page exist or not. Also, i suspect the exception is making my code slow (i tested it)

static public bool CheckExist(string url)
        {
            HttpWebRequest wreq = null;
            HttpWebResponse wresp = null;
            bool ret = false;

            try
            {
                wreq = (HttpWebRequest)WebRequest.Create(url);
                wreq.KeepAlive = true;
                //wreq.Method = "HEAD";
                wresp = (HttpWebResponse)wreq.GetResponse();
                ret = true;
            }
            catch (System.Net.WebException)
            {
            }
            finally
            {
                if (wresp != null)
                    wresp.Close();
            }
            return ret;
        }
From stackoverflow
  • The HttpWebResponse class exposes a StatusCode property which returns a value from the HttpStatusCode enum. In the non-error case, this directly gives you the status code (404 not found, 403 unauthorised, 301 moved permanently, 200 OK and so on). In the error case, the WebException class exposes a Status property - taken from a different enum, but you'll be able to identify the cases you want from that I'd have thought.

    acidzombie24 : I think your saying theres no way to get the page status w/o having an exception when its 404/403/etc. I'll keep this in mind.
    David M : Yes, the behaviour for one of these "erroring" HTTP statuses is to throw a WebException.
  • You can get the http error code like this:

    catch (System.Net.WebException e)
    {
        int HttpStatusCode = (int)((HttpWebResponse)e.Response).StatusCode;
    }
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.