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?