I have been trying to use OkHttp and Retrofit to cache http requests. But I dont seem to figure why it isnt working.
@Headers("Cache-Control: public, max-age=640000, s-maxage=640000 , max-stale=10000000")
@FormUrlEncoded
@POST("/news/getNewslist/")
void newsListByGenre(@Field("news_genre") String genre,
Callback<ArrayList<NewsStory>> callback);
This is one of the requests, it has all the required headers. Moreover, in an attempt to test that something is written to File Cache I manually assigned a cache to OkHttpClient.
OkHttpClient name = new OkHttpClient();
try {
if (!cache.exists())
cache.createNewFile();
name.setResponseCache(new HttpResponseCache(cache,
10 * 1024 * 1024));
} catch (IOException e) {
e.printStackTrace();
}
The file cache I created has only 36 bytes, so I am sure nothing is cached.
I have also tried to make sure that the server has required headers, although I want it to work without server interference but I set the cache control headers in the request as well. This is the debug log from retrofit.
null: HTTP/1.1 200 OK
Cache-Control: public, max-age=360000
Connection: Keep-Alive
Content-Length: 5167
Content-Type: application/json
Date: Fri, 28 Jun 2013 01:00:22 GMT
Keep-Alive: timeout=5, max=99
Server: Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7
X-Android-Received-Millis: 1372381311315
X-Android-Response-Source: NETWORK 200
X-Android-Selected-Transport: http/1.1
X-Android-Sent-Millis: 1372381311048
X-Powered-By: PHP/5.4.7
I have read the caching mechanism of http again and again but seems I am missing something.
Caching is nothing but a way to store network fetched data on a device's storage and access later when the device is offline or we want the same data again and again.
HTTP caching occurs when the browser stores local copies of web resources for faster retrieval the next time the resource is required. As your application serves resources it can attach cache headers to the response specifying the desired cache behavior.
android.net.http.HttpResponseCache. Caches HTTP and HTTPS responses to the filesystem so they may be reused, saving time and bandwidth. This class supports HttpURLConnection and HttpsURLConnection ; there is no platform-provided cache for DefaultHttpClient or AndroidHttpClient .
"Responses to POST method are not cacheable, UNLESS the response includes appropriate Cache-Control or Expires header fields." So, YES, you can cache POST request response but only if it arrives with appropriate headers. In most cases you don't want to cache the response.
You can't really cache POST
responses. Use the GET
method instead. Here's a working example of a Retrofit and OkHttp with caching:
https://gist.github.com/swankjesse/5889518
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With