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);
                    }
                }
            }
        }
    }
}

上一篇:seo步骤


下一篇:在Python中用Request库模拟登录(一):字幕库(无加密,无验证码)