http clients that dont throw on error

社会主义新天地 提交于 2021-02-08 08:56:59

问题


I am looking for c# HTTP client that doesn't throw when it gets an HTTP error (404 for example). This is not just a style issue; its perfectly valid for a non 2xx reply to have a body but I cant get at it if the HTTP stack throws when doing a GetResponse()


回答1:


All the System.Net.Http.HTTPClient methods that return Task<HttpResponseMessage> do NOT throw on any HttpStatusCode. They only throw on timeouts, cancellations or inability to connect to a gateway.




回答2:


If you are using the HttpClient in System.Net.Http, you can do something like this:

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.
    }
}

Since almost all methods on HttpClient are thread safe, I suggest you actually create a static client to use elsewhere in your code, that way you aren't wasting memory if you make a lot of requests by constantly creating a destroying clients for just one request when they can make thousands.




回答3:


What about implementing a class that is wrapping the HttpClient?

Let it implement the desired methods which are delegated to the client object and try/catch the exceptions in these delegating methods.

class MyClient 
{
    HttpClient client;

    [...]

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

After implementing your own client, you'll get rid of these exceptions.

If you need a HttpClient instance, inherit from HttpClient and override it's methods it like this:

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


来源:https://stackoverflow.com/questions/20478328/http-clients-that-dont-throw-on-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!