1
RetrofitとOkHttpを使用してキャッシュを実装しようとしています。オフライン時に「504要求不能(リクエストがキャッシュされている場合のみ)」というエラーが表示されます。Retrofit2.1.0とokhttp3オフラインキャッシュが機能しない
OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
builder.readTimeout(10, TimeUnit.SECONDS);
builder.connectTimeout(5, TimeUnit.SECONDS);
if (isDebug) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(logging);
}
builder.addNetworkInterceptor(REWRITE_RESPONSE_INTERCEPTOR)
.addInterceptor(OFFLINE_INTERCEPTOR)
.cache(provideCache());
OkHttpClient client = builder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(base_url)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
reqinterface = retrofit.create(MyApiInterface.class);
private static Cache provideCache(){
Cache cache = null;
try{
cache = new Cache(new File(context.getCacheDir(),"baskin-cache"),
10*1024*1024);
}catch (Exception e){
Log.i("zacharia","Could not create Cache");
}
return cache;
}
private static final Interceptor REWRITE_RESPONSE_INTERCEPTOR = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
okhttp3.Response originalResponse = chain.proceed(chain.request());
String cacheControl = originalResponse.header("Cache-Control");
if (cacheControl == null || cacheControl.contains("no-store") || cacheControl.contains("no-cache") ||
cacheControl.contains("must-revalidate") || cacheControl.contains("max-age=0")) {
return originalResponse.newBuilder()
.header("Cache-Control", "public, max-age=" + 120)
.build();
} else {
return originalResponse;
}
}
};
private static final Interceptor OFFLINE_INTERCEPTOR = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!isOnline()) {
Log.d("zacharia", "rewriting request");
int maxStale = 60 * 60 * 24 * 7; // tolerate 4-weeks stale
request = request.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
.build();
}
return chain.proceed(request);
}
};
public static boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
オンラインでは、ログに 'D/OkHttp:Cache-Control:public、max-age = 120'が表示されます。オフライン時に、「D/OkHttp:<から504充足不能要求(のみ-IF-キャッシュされた)」
質問したところで解決策を見つけましたか? – Bogy