HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

时间:2023-03-08 17:25:12
HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

参考: .Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned
C# code

using System;
using System.IO;
using System.Net;
 
public class Test
{
    static void Main()
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://csharpindepth.com/asd");
        try
        {
            using (Stream data = request.GetResponse().GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(data))
                {
                    string text = reader.ReadToEnd();
                    Console.WriteLine(text);
                }
            }
        }
        catch (WebException ex)
        {
            HttpWebResponse response = (HttpWebResponse) ex.response;
            Console.WriteLine("Error code: {0}", response.StatusCode);
            if (response.StatusCode == HttpStatusCode.BadRequest)
            {
                using (Stream data = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(data))
                    {
                        string text = reader.ReadToEnd();
                        Console.WriteLine(text);
                    }
                }
            }
        }
    }
}