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?
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With