HttpWebRequest, HttpWebResponse, and the WebException

Standard

Calling the GetResponse() method on the HttpWebRequest class yields some interesting results. It determines that a status code of anything else but 200 (OK) is an exceptional case and throws a WebException exception.

The following code demonstrates how to return the status code even if the URL in the request is not OK.

HttpStatusCode httpStatusCode;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://invalidsitename.net/");
try
{
    using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
    {
        httpStatusCode = httpWebResponse.StatusCode; //OK
    }
}
catch (WebException webException)
{
    if (webException.Response != null)
    {
        HttpWebResponse httpWebExceptionResponse = (HttpWebResponse)webException.Response;
        httpStatusCode = httpWebExceptionResponse.StatusCode; //Something other than OK
    }
    else
    {
        throw webException; //Invalid host name
    }
}
return httpStatusCode;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s