Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

http clients that dont throw on error

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()

like image 581
pm100 Avatar asked Sep 05 '25 16:09

pm100


2 Answers

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.

like image 77
Darrel Miller Avatar answered Sep 07 '25 13:09

Darrel Miller


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.

like image 41
Pete Garafano Avatar answered Sep 07 '25 12:09

Pete Garafano