16
votes

I need to read the response from an HTTP GET in situations where the Response Status code is not 200 OK. Sometimes it is 401, other 403, however there will be a Response content. If I try to use the HttpWebResponse and HttpWebRequest classes, it throws an exception when the response status is not 200 OK. Any suggestions?

1

1 Answers

38
votes
var request = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com/1");
try
{
    using (WebResponse response = request.GetResponse())
    {
        // Success
    }
}
catch (WebException e)
{
    using (WebResponse response = e.Response)
    {
        HttpWebResponse httpResponse = (HttpWebResponse)response;
        Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
        using (var streamReader = new StreamReader(response.GetResponseStream()))
            Console.WriteLine(streamReader.ReadToEnd());
    }
}