HttpWebRequest, HttpWebResponse, and the WebException


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("");
    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
        throw webException; //Invalid host name
return httpStatusCode;

Leave a Reply

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

You are commenting using your 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