2013-03-11 94 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

相關問題