22

我基本上在寻找这里问的同样的事情: 当服务器返回错误时,任何方法可以使用 WebClient 访问响应正文?

但到目前为止还没有给出答案。

服务器返回“400 错误请求”状态,但带有详细的错误说明作为响应正文。

关于使用 .NET WebClient 访问该数据的任何想法?当服务器返回错误状态代码时,它只是抛出异常。

4

2 回答 2

24

您无法从 webclient 获取它,但是在您的 WebException 上,您可以访问将其转换为 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);
        }
    }
}
于 2013-03-11T19:53:41.970 回答
22

您可以像这样检索响应内容:

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上

于 2018-01-28T17:11:04.453 回答