WebClient - 获取错误状态码的响应体

23

我基本上是在寻找与此处提出的内容相同的东西:当服务器返回错误时,使用WebClient访问响应正文的任何方法?

但迄今为止还没有提供答案。

服务器返回“400 bad request”状态,但响应正文中包含了详细的错误说明。

有什么办法可以使用.NET WebClient访问那些数据吗?它只会在服务器返回错误状态码时抛出异常。


4
这个问题可能会有所帮助:https://dev59.com/R2w05IYBdhLWcg3wxkqr - Claudio Redi
请参考以下链接:https://dev59.com/Gmgt5IYBdhLWcg3wxARj - I4V
2个回答

32

你无法从Web客户端获取它,但在WebException中,你可以访问Response对象,并将其转换为HttpWebResponse对象,这样你就能够访问整个响应对象。

请参见WebException类定义以获取更多信息。

以下是MSDN中的示例(为了清晰起见,添加了读取Web响应内容):

using System;
using System.IO;
using System.Net;

public class Program
{
    public static void Main()
    {
        try {
            // Create a web request for an invalid site. Substitute the "invalid site" strong in the Create call with a invalid name.
            HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid URL");

            // Get the associated response for the above request.
            HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();
            myHttpWebResponse.Close();
        }
        catch(WebException e) {
            Console.WriteLine("This program is expected to throw WebException on successful run."+
                              "\n\nException Message :" + e.Message);
            if(e.Status == WebExceptionStatus.ProtocolError) {
                Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                using (StreamReader r = new StreamReader(((HttpWebResponse)e.Response).GetResponseStream()))
                {
                    Console.WriteLine("Content: {0}", r.ReadToEnd());
                }
            }
        }
        catch(Exception e) {
            Console.WriteLine(e.Message);
        }
    }
}

1
我知道它使用的是HttpWebRequest,但对于WebClient来说也是一样的,因为所有方法都可以返回WebException。 - dmportella

26
您可以像这样检索响应内容:
using (WebClient client = new WebClient())
{
    try
    {
        string data = client.DownloadString(
            "http://your-url.com");
        // successful...
    }
    catch (WebException ex)
    {
        // failed...
        using (StreamReader r = new StreamReader(
            ex.Response.GetResponseStream()))
        {
            string responseContent = r.ReadToEnd();
            // ... do whatever ...
        }
    }
}

测试结果:在 .Net 4.5.2 上进行


5
这应该是被接受的答案,因为它展示了如何获取响应的正文内容。 - Roland
太棒了!符合预期 - 谢谢 - WiiLF

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接