2013-03-11 65 views
7

我期待基本上是在这里问了同样的事响应体: Any way to access response body using WebClient when the server returns an error?WebClient的 - 会在错误状态代码

但没有答案,迄今已提供。

服务器返回一个“400错误请求”状态,但具有详细的错误说明作为响应主体。

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

+4

此其他问题可能有所帮助:http://stackoverflow.com/questions/7036491/get-webclient-errors-as-string – 2013-03-11 18:58:47

+0

而这个http://stackoverflow.com/问题/ 11828843/c-sharp-webexception-how-to-get-whole-response-with-a-body – I4V 2013-03-11 19:09:51

回答

8

你不能从webclient获取它,但是在你的WebException中,你可以访问Response Object将它转换为HttpWebResponse对象,并且你将能够访问整个响应对象。

有关更多信息,请参见WebException类定义。

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

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); 
} 
+0

我知道它使用HttpWebRequest,但它与WebClient相同,因为所有方法都可以返回WebException – dmportella 2013-03-11 20:00:27

0

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

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

相关问题