Dave Anderson
Dave Anderson

Reputation: 438

Xamarin Forms app, HttpClient seemingly caching responses FOREVER

I'm in the testing phase of my first Xamarin.Forms app, which relies heavily on the HttpClient to retrieve JSON data from a remote site. I've found that once a request has been made, the response seems to be cached and updated data is never retrieved. I'm initializing the HttpClient like this:

new HttpClient()
{
  Timeout = new TimeSpan(0, 0, 1, 0),
  DefaultRequestHeaders =
  {
    CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store, must-revalidate"),
    Pragma = { NameValueHeaderValue.Parse("no-cache")}
  }
}

Those request headers didn't seem to help at all. If I put one of the URLs in my browser, I get the JSON response with the updated data. The server side is setting a no-cache header as well.

Any idea how I can FORCE a fresh request each time? TIA. This testing is being done in an Android emulator, btw. I don't know yet whether the iOS build is behaving similarly.

Upvotes: 0

Views: 1121

Answers (1)

Erik J.
Erik J.

Reputation: 809

I'd suggest you use the modernhttpclient nuget package, and implement your android code like:

var httpClient = new HttpClient(new NativeMessageHandler());

This code works on both android, iOS and/or code in a PCL. Basically this nuget package makes sure that you are using the latest platform optimizations for the HttpClient. For Android this is the OkHttp-package, for iOS this is NSURLSession.

This helps you prevent any of the quirks of the provided HttpClient class, and use the optimizations that the platform you're running offers you.

Issues like the one you show should no longer happen.

Upvotes: 1

Related Questions