2

I'm trying to get caching to work with Retrofit with no luck, and I'm not quite sure what I'm doing wrong.

Using:

build.gradle

compile 'com.squareup.okhttp:okhttp:1.5.+'
compile 'com.squareup.retrofit:retrofit:1.5.+'

Example Call

@Headers("Cache-Control: public, max-age=640000, s-maxage=640000 , max-stale=10000000")
@GET("/articles/{article}")
public void getArticle(
    @Path("article") String id,
    Callback<Article> cb
);

Building the API

File cacheDir = context.getCacheDir();
cache = null;
try {
    cache = new HttpResponseCache(cacheDir, 10 * 1024 * 1024);
} catch (IOException e) {
    e.printStackTrace();
}

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setResponseCache(cache);
OkClient okClient = new OkClient(okHttpClient);

api = new RestAdapter.Builder()
   .setEndpoint(TestAPI.BASE_URL)
   .setRequestInterceptor( ... only adding path params ... )
   .setClient(okClient)
   .build()
   .create(TestAPI.class);

The call works, the only issue is actually getting it to cache... I'm checking against cache.getHitCount() after I make my calls to check if there was anything that cached, and it always turns up as 0.

Brandon Romano
  • 1,022
  • 1
  • 13
  • 21
  • 1
    OkHttp automatically process cache based on [HTTP standart](http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html). I would suggest to print logs and see if your server correctly forms Cache-control header and indicates that request could be cached on client. Most likely you do not need to tweak headers on client, but config server instead. – Sergii Pechenizkyi Apr 17 '14 at 18:40
  • Thanks, I ended up going with a different solution out of another necessity, but I hope your comment helps lead others to the right solution! – Brandon Romano Apr 18 '14 at 22:32
  • By any chance, did you return back to this issue and solved it? I have got a similar issue: http://stackoverflow.com/questions/24467416/retrofit-cache-control-never-included-in-response but for Retrofit 1.6.0 – Amio.io Jul 02 '14 at 14:29
  • Hey @zatziky, I ended up needing a more flexible cache solution for another reason, so I wrote a Cache Library that fit my needs called [CREAM](https://github.com/carrot/cream). There's some examples in there to get you started if you wanted to go that route. If you have any questions about it shoot me an email (on my stackoverflow profile). – Brandon Romano Jul 02 '14 at 15:10

1 Answers1

0

Check this.

public InterfaceRequests  getProductListAdapter(final AppCompatActivity appCompatActivity) {
        File httpCacheDirectory = new File(appCompatActivity.getCacheDir(), "responses");

        Cache cache = null;
        try {
            cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
        } catch (IOException e) {
            Log.e("OKHttp", "Could not create http cache", e);
        }

        OkHttpClient okHttpClient = new OkHttpClient();
        if (cache != null) {
            okHttpClient.setCache(cache);
        }

        InterfaceRequests getReportList = new RestAdapter.Builder()
                .setEndpoint(InterfaceRequests.aPIBaseURL)
                .setClient(new OkClient(okHttpClient))
                .setRequestInterceptor(new RequestInterceptor() {
                    @Override
                    public void intercept(RequestFacade request) {
                        request.addHeader("Accept", "application/json;versions=1");
                        if (CheckForInternetConnection.isNetworkAvailable(appCompatActivity)) {
                            int maxAge = 60; // read from cache for 1 minute
                            request.addHeader("Cache-Control", "public, max-age=" + maxAge);
                        } else {
                            int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
                            request.addHeader("Cache-Control",
                                    "public, only-if-cached, max-stale=" + maxStale);
                        }
                    }
                })
                .build()
                .create(InterfaceRequests.class);

        return getReportList;
    }
abozaid
  • 967
  • 8
  • 11