Web客户端 - 得到响应主体的错误状态码 [英] WebClient - get response body on error status code

查看:182
本文介绍了Web客户端 - 得到响应主体的错误状态码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上是在寻找同样的东西在这里问:
以任何方式使用Web客户端时,服务器将返回错误访问响应主体?

I'm looking essentially for the same thing asked here: Any way to access response body using WebClient when the server returns an error?

不过,没有答案,迄今已提供。

But no answers have been provided so far.

该服务器会返回400错误的请求的地位,但有一个详细的错误解释响应体。

The server returns a "400 bad request" status, but with a detailed error explanation as response body.

在访问与.NET Web客户端的数据任何想法?它只是抛出时,服务器返回一个错误状态代码异常。

Any ideas on accessing that data with .NET WebClient? It just throws an exception when server returns an error status code.

推荐答案

您不能从Web客户端得到它可是你的引发WebException可以访问响应对象强制转换成一个HttpWebResponse对象,并将能够访问整个响应对象。

You cant get it from the webclient however on your WebException you can access the Response Object cast that into a HttpWebResponse object and you will be able to access the entire response object.

请看到的引发WebException 类定义的更多信息。

Please see the WebException class definition for more information.

下面是从MSDN的例子(不最好的方式来处理异常,但它应该给你一些想法)

Below is an example from MSDN (is not the best way to handle the exception but it should give you some idea)

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 site");

    // 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);
    }
}
catch(Exception e) {
    Console.WriteLine(e.Message);
}

这篇关于Web客户端 - 得到响应主体的错误状态码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆