我有一个使用OkHTTP进行Retrofit的实现作为配置了Interceptor的客户端来启用缓存功能。好吧缓存工作正常,但我无法使用我已有的机制禁用缓存。我确实有一个解决方案:不使用Code Containing缓存机制,每次我想禁用Cache时都使用正常的改进实现。
这是完整代码。 Service Generator将改造接口转换为可重用的客户端。并请求请求/响应拦截器
package com.example.infinite.adapter;
import android.content.Context;
import android.util.Log;
import com.example.infinite.settings.Config;
import com.example.infinite.utils.ConnectionDetector;
import com.example.infinite.utils.SharedPreferenceEasy;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.android.MainThreadExecutor;
import retrofit.client.OkClient;
/**
* Created by user on 5/18/2015.
* Create REST Adapter for Given Class
*/
public class ServiceGenerator {
protected static RestAdapter mRestAdapter;
static String secret = "Schhh!!";
private static Context mContext;
private static final Interceptor mCacheControlInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// Add Cache Control only for GET methods
if (request.method().equals("GET")) {
//see if cache is enabled
if (enableCache) {
if (new ConnectionDetector(mContext).isConnectingToInternet()) {
// 1 day
request.newBuilder()
.header("Cache-control", "only-if-cached")
.header("Accept", "application/json")
.header("Authorization", "Basic " + secret)
.build();
Log.d("REQUEST CACHE", "Only-if-Cached");
} else {
// upto 4 weeks stale
request.newBuilder()
.header("Cache-control", "public, max-stale=2419200")
.header("Accept", "application/json")
.header("Authorization", "Basic " + secret)
.build();
Log.d("REQUEST CACHE", "MAX STALE ");
}
}else
{
//NO CACHE
request.newBuilder()
.header("Cache-control" ,"public,max-age=0")
.header("Accept", "application/json")
.header("Authorization", "Basic " + secret)
.build();
Log.d("REQUEST CACHE","NO CACHE ");
}
}
//s-maxage for requests with authentications
Response response = chain.proceed(request);
// Re-write response CC header to force use of cache & set header such that it is cached.
if(enableCache) {
Log.d("RESPONSE CACHE","MAXAGE-CACHE ");
return response.newBuilder()
.header("Cache-control", "public, max-age=86400") // 1 day
.header("Accept", "application/json")
//Authentication Header , do you want to see it in the response
.header("Authorization", "Basic " + secret)
.build();
}else{
Log.d("RESPONSE CACHE","NO-CACHE ");
//Say that you don't want the result to be storedcontinue
return response.newBuilder()
.header("Cache-control", " public,max-age=0, no-cache, no-store,must-revalidate")
.header("Pragma","no-cache")
.build();
}
}
};
/**
* @param serviceClass Service class To create the adaptor for
* @param baseUrl Base URL of the API
* @param context Used to create a Cache
* @param <S>
* @return Rest Adapter
*/
public static <S> S createService(Class<S> serviceClass, String baseUrl, Context context) {
mContext = context;
enableCache = new SharedPreferenceEasy(context).RetreiveBoolean(Config.KEY_PREF_NETWK_CACHE,true);
// Create Cache
Cache cache = null;
cache = new Cache(new File(mContext.getCacheDir(), "http"), SIZE_OF_CACHE);
// Create OkHttpClient
OkHttpClient okHttpClient = new OkHttpClient();
if(enableCache) {
okHttpClient.setCache(cache);
}
okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
okHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
// Add Cache-Control Interceptor
okHttpClient.networkInterceptors().add(mCacheControlInterceptor);
// Create Executor
Executor executor = Executors.newCachedThreadPool();
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(baseUrl)
.setExecutors(executor, new MainThreadExecutor())
.setClient(new OkClient(okHttpClient))
.setLogLevel(RestAdapter.LogLevel.FULL);
RestAdapter adapter = builder.build();
return adapter.create(serviceClass);
}
}
我想从我的应用设置中禁用缓存时,从网络获得强制性请求。 if(enableCache)