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

Posted MicrobeORM

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
                    }
                }
            }
        }
    }
}

以上是关于HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned(示例的主要内容,如果未能解决你的问题,请参考以下文章