在响应状态代码不是200 OK的情况下,我需要从HTTP GET读取响应。有时是401,其他是403,但会有响应内容。如果我尝试使用HttpWebResponse和HttpWebRequest类,当响应状态不是200 OK时,它会抛出异常。有什么建议吗?
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());
}
}