WebException获取详细内容 记录

http://bbs.csdn.net/topics/390883361

来自此处.

问题.某个接口.返回错误消息用的是400.所以必须知道具体的内容.

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);
                    }
                }
            }
        }
    }
}
感谢@save4me
posted @ 2017-04-01 11:47  forhells  阅读(2895)  评论(0编辑  收藏  举报