How to check caching in DefaultHttpClient on Android

My Android application requires caching response text from a web service call using DefaultHttpClient. The cache must be valid until the expiration time specified in the Http response header expires.

I found similar questions, but they were complaints that DefaultHttpClient caches its answers. Funny, I need it, but I could not work. Or file-based solutions are suggested.
Does Android support uploading images from HTTP to cache?
how to do image caching in android

I wrote an example application that requests a URL when a button is clicked and prints the response status and headers.

DefaultHttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); HttpResponse response; response = client.execute(request); System.out.println("Response status - " + response.getStatusLine().getStatusCode()); 

And my servlet code is GAE,

 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/plain"); resp.setHeader("Expires", "Wed, 11 Jul 2012 12:00:00 GMT"); resp.setHeader("Cache-Control", "max-age=2592000"); resp.getWriter().println("Hi!"); } 

Pressing the button each time gives me a status code of 200. I expect that this should be only the first time.

 Response status - 200 ***** Response Headers ***** Content-Type - text/plain; charset=iso-8859-1 Expires - Wed, 11 Jul 2012 12:00:00 GMT Cache-Control - max-age=2592000 Date - Wed, 13 Jul 2011 06:54:57 GMT Server - Google Frontend Transfer-Encoding - chunked 

I edited the servlet and published; the client reads the last change. I tested the servlet application in Chrome browser and caching works fine.

I added the Cache-control property to the request header, but did not get the expected result.

How to ensure that DefaultHttpClient caches the contents of the response and does not send a request to the server before the expiration date?

+4
source share
2 answers

This CachingHttpClient is probably what you are looking for, it's just the DefaultHttpClient decorator.

Please note that in Android only HttpClient 4.0, for the example code to work in android, you need to add the dependencies HttpClient 4.1 and HttpClient Cache 4.1 to your project.

+2
source

You can use this .

Its library is 704kb and contains a parallel implementation of httpclient 4.1 compiled for Android. It contains CachingHttpClient and many bug fixes. However, use this only if the in-memory memory cache is useful to you. Therefore, if your application makes the same api call many times during the same session, the performance impact will be visible.

0
source

All Articles