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()
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With