How to check caching in DefaultHttpClient on Android
My Android application requires to cache the response text from a web service call using DefaultHttpClient. The cache should be valid till the expiry time set in the Http response header.
I found similar questions but they were complaints that the DefaultHttpClient is caching their responses. Funny I need it but could not get working. Or there solutions suggested that are file based.
Does Android开发者_如何学JAVA keeps the images downloaded from HTTP in cache? how to do image caching in androidI wrote a sample app that requests for a url on click of a button 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 GAE servlet code is,
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!");
}
Clicking on the button the every time gives me the status code as 200. I expect this should be the case for the first time only.
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 latest change. I tested the servlet application on Chrome browser and caching works fine.
I added the Cache-control property in the request header, but did not get the expected result.
How do I ensure the DefaultHttpClient caches the response content and does not send request to the server again until the expiry time?
This CachingHttpClient is probably what you looking for, it is simply a decorator to the DefaultHttpClient.
Note that android only include HttpClient 4.0, in order to make the sample code works in android, you need add dependencies HttpClient 4.1 and HttpClient Cache 4.1 into your project.
You can use this.
Its a 704kb library and contains a parallel implementation of httpclient 4.1 compiled for Android.
It contains CachingHttpClient
and many bug fixes as well. However only use if in-memory cache is useful for you. So if your application makes the same api call many times during one session the performance impact will be visible.
精彩评论