2013-12-09 59 views
1

我正在尋找C#HTTP客戶端,它不會拋出,當它得到一個HTTP錯誤(404例如)。 這不僅僅是一個風格問題;它完全有效的非2xx答覆有一個身體,但我不能得到它,如果HTTP堆棧拋出時做一個GetResponse()http客戶端,不會拋出錯誤

+3

你可以得到的迴應 http://stackoverflow.com/questions/692342/net-httpwebrequest-getresponse-raises-exception-when-http-status-code-400-ba HTTP ://stackoverflow.com/questions/18403846/httpwebrequest-accept-500-internal-server-error – CaldasGSM

+0

@ CaldasGSM - 啊哈 - 我沒有意識到 - ty – pm100

回答

3

所有返回Task<HttpResponseMessage>System.Net.Http.HTTPClient方法不是扔在任何HttpStatusCode上。他們只會拋出超時,取消或無法連接到網關。

0

實現一個包裝HttpClient的類是什麼?

讓它實現委託給客戶端對象的所需方法,並嘗試/捕獲這些委託方法中的例外。

class MyClient 
{ 
    HttpClient client; 

    [...] 

    public String WrappedMethodA() 
    { 
     try { 
      return client.MethodA(); 
     } catch(Exception x) { 
      return ""; // or do some other stuff. 
     } 
    } 
} 

實施自己的客戶端後,您將擺脫這些例外。

如果你需要一個HttpClient的實例,從HttpClient的繼承和重寫它的方法是這樣的:

public String WrappedMethodA() 
    { 
     try { 
      return base.MethodA(); // using 'base' as the client object. 
     } catch(Exception x) { 
      return ""; // or do some other stuff. 
     } 
    } 
2

如果您使用的是System.Net.Http HttpClient的,你可以做這樣的事情:

using (var client = new HttpClient()) 
using (var response = await client.SendAsync(request)) 
{ 
    if (response.IsSuccessStatusCode) 
    { 
     var result = await response.Content.ReadAsStreamAsync(); 
     // You can do whatever you want with the resulting stream, or you can ReadAsStringAsync, or just remove "Async" to use the blocking methods. 
    } 
    else 
    { 
     var statusCode = response.StatusCode; 
     // You can do some stuff with the status code to decide what to do. 
    } 
} 

由於在HttpClient的幾乎所有方法都是線程安全的,我建議你真正創建一個靜態的客戶端代碼中的其他地方使用,你是不是浪費內存的方式,如果你賺了很多的請求通過不斷創造摧毀客戶只有一個請求時埃可以做成千上萬。

相關問題