Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Get Web Response when HTTP Status is NOT 200 OK

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?

like image 768
Steve Kiss Avatar asked Jun 03 '11 02:06

Steve Kiss


1 Answers

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());
    }
}
like image 70
Alex Aza Avatar answered Oct 13 '22 00:10

Alex Aza