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 Answer
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());
    }
}
3 Comments
vapcguy
 Except if 
  response in the catch is null, like it was for me, then it throws another exception and is utterly useless...  I was testing with a deliberately disconnected server, though.  My exception "Unable to connect to the remote server" was good enough for me for that.  But yeah, normally exceptions are light on the Status Codes and details for other issues.  My advice with this code - just handle for null response - probably  return e.ToString(); would be good enough for that case.vapcguy
 AND NEXT TIME -- add a 
  request.Credentials = CredentialCache.DefaultCredentials; as the 2nd line to this code!!  I kept getting (401) Unauthorized errors and couldn't figure it out, because I was calling a web service where I had added that line, and then I was trying this code!  Gotta do it to this one, too!vapcguy
 And this code doesn't deliver the 
  401, it will say Unauthorized for the StatusCode.