Pinser
Pinser

Reputation: 1896

Cannot achieve HTTP caching in android

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.

Upvotes: 6

Views: 4648

Answers (2)

lstanczyk
lstanczyk

Reputation: 1393

@Jesse Wilson - I think that it makes sense to cache the response sometimes - I am working on an app that makes network call but if user switches activities and comes back I would like to use the same data as previously returned by the POST response. I know I can use ORM and persist mu objects etc, just seems like it would be so much easier to tell retrofit to use the same response.

Upvotes: 0

Jesse Wilson
Jesse Wilson

Reputation: 40595

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

Upvotes: 8

Related Questions