2

我试图让缓存与 Retrofit 一起工作,但没有运气,我不太确定我做错了什么。

使用:

构建.gradle

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

示例调用

@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
);

构建 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);

该调用有效,唯一的问题实际上是将其缓存...我在调用后检查 cache.getHitCount() 以检查是否有任何缓存的内容,并且它始终显示为 0。

4

1 回答 1

0

检查这个。

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;
    }
于 2015-10-08T09:37:38.640 回答