WebClient - 获取错误状态代码的响应正文

问题描述 投票:13回答:2

我基本上都在寻找同样的问题:Any way to access response body using WebClient when the server returns an error?

但到目前为止还没有提供任何答案。

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

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

c# webclient bad-request
2个回答
13
投票

您无法从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);
        }
    }
}

6
投票

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

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上

© www.soinside.com 2019 - 2024. All rights reserved.