繁体   English   中英

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

[英]WebClient - get response body on error status code

我基本上都在寻找同样的问题: 当服务器返回错误时,使用WebClient访问响应体的方法是什么?

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

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

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

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

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

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上

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM