我试图让缓存与Retrofit合作而没有运气,而且我不太确定我做错了什么。
使用:
的build.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。
答案 0 :(得分: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;
}