If you read my previous article, it’s easy to become frustrated. HttpClient is at the core of everything we as software developers normally do when we integrate our stuff with other people’s stuff. Somebody sounding the alarm, telling you that it’s fundamentally broken, might result in everything ranging from a general concern about ones own code, to flat out panic attacks. Hence, I figured I’d be an asshole unless I also showed you an alternative.

Paradoxically, fixing HttpClient is very easy, it’s just to cut away everything in it that’s dangerous, and encapsulate everything that’s beautiful about it into a much safer API, making it impossible for developers to retrieve the instance to the HttpClient you’re using internally. Basically, treat most of HttpClient’s API as if it was cancer, and salvage the rest. Here’s a much safer version in case you care. For the record, to understand this class, you have to read my previous article here at DZone.

As an additional bonus, it also automatically converts to and from request/response types automatically, using some intelligent generic constructs, allowing you to consume it in a much more “functional style”. After all, HTTP is fundamentally a functional thing, and implementing too much OO constructs in it, is like using a hammer to fix your chimney. Check out basic usage of it below to understand what I mean.

FYI – You can retrieve an instance to IHttpClient using dependency injection.

As an additional bonus, you can also both transmit and receive Streams. Its GET implementation has an overload allowing you to supply an Action, that will be invoked when the response stream is ready, allowing you to request very large documents, and accessing the stream response directly. This allows you to persist very large documents to for instance disc, without loading them into memory first. It also has overloads for both its POST and PUT methods, allowing you to pass in a Stream object as its payload, at which point it will copy the stream’s content, and transmit it over the HTTP request stream object. These are “advanced” features, but allows you to for instance send a 100MB large file as an HTTP request’s payload, never consuming more than some few kilobytes on the server transmitting the document.

But the most beautiful part, is that it’s a simple C# file, completely encapsulating HttpClient, that never gives your noob developers access to any of the features, that might result in them blowing off their feet. It’s licensed as LGPL allowing you to use it for free …

Architecture is about getting rid of complexity, not adding it



Source link

Write A Comment