4

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

pm100
  • 48,078
  • 23
  • 82
  • 145
  • 3
    you can get the response 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 Dec 09 '13 at 18:55

3 Answers3

9

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.

Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
3

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.

Pete Garafano
  • 4,863
  • 1
  • 23
  • 40
-2

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.
        }
    }
rulebot
  • 232
  • 3
  • 7