9: Handling Authentication, Sessions and Caching

Making multiple round-trips

At its simplest, HTTP is just a “request & response” protocol. Of course, when redirection happens, subsequent requests may occur, following the redirection, which HttpClient supports transparently by default.

But three other aspects mean that we have to be able to aggregate context over a series of requests:

  • when authenticating, the server might issue challenges, meaning that there might be several “request & response” round-trips.

  • when using cookies, those cookies that were sent from the server on earlier requests are returned to the server on subsequent requests.

  • when using a performance-enhancing cache, subsequent requests can be abbreviated or skipped entirely, provided they match data from an earlier request.

Most of the tutorial so far has dealt with the basic HttpClient, which is stateless. But there is an alternative, HttpBrowser, that provides the statefulness needed for all multi-request traffic.

Both HttpClient and HttpBrowser share the common Http trait. HttpBrowser contains an instance of HttpClient for making the actual requests.

Authentication

This was described on the previous page.

This was described on an earlier page; you can roll your own using HttpClient. But you don’t need to: there is a simple feature of HttpBrowser: it holds one cookie jar and automatically applies those cookies to all its requests.

If you need more than one distinct collection of state, simply use multiple instances of HttpBrowser, each of which will maintain its own jar of cookies independently of the others.

Caching

Caching is the major new topic introduced here. The constructor of HttpBrowser can accept a Cache parameter. The default behaviour of HttpBrowser is to cache nothing, but if you supply an instance of InMemoryCache to it, then cachable responses will reduce the network traffic accordingly.

You may share a single InMemoryCache across many instances of HttpBrowser if you need to.

…Alas, the rest of this page is still in preparation…