How Retrofit with OKHttp use cache data when offline

后端 未结 1 1380
你的背包
你的背包 2021-01-31 11:21

I want to Retrofit with OkHttp uses cache when is no Internet.

I prepare OkHttpClient like this:

    RestAdapter.Builder builder= new RestAdapter.Builder         


        
相关标签:
1条回答
  • 2021-01-31 12:16

    I have simlar problem in my company :)

    The problem was on server side. In serwer response i have:

    Pragma: no-cache
    

    So when i removed this everything starts working. Before i removed it i get all the time such exceptions: 504 Unsatisfiable Request (only-if-cached)

    Ok so how implementation on my side looks.

        OkHttpClient okHttpClient = new OkHttpClient();
    
        File httpCacheDirectory = new File(appContext.getCacheDir(), "responses");
    
        Cache cache = new Cache(httpCacheDirectory, maxSizeInBytes);
        okHttpClient.setCache(cache);
    
        OkClient okClient = new OkClient(okHttpClient);
    
        RestAdapter.Builder builder = new RestAdapter.Builder();
        builder.setEndpoint(endpoint);
        builder.setClient(okClient);
    

    If you have problems in testing on which side is problem (server or app). You can use such feauture to set headers received from server.

    private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse.newBuilder()
                                   .removeHeader("Pragma")
                                   .header("Cache-Control",
                                           String.format("max-age=%d", 60))
                                   .build();
        }
    };
    

    and simply add it:

    okHttpClient.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);
    

    Thanks to that as you can see i was able to remove Pragma: no-cache header for test time.

    Also i suggest you to read about Cache-Control header:

    max-age,max-stale

    Other usefull links:

    List of HTTP header fields

    Cache controll

    Another sample code

    0 讨论(0)
提交回复
热议问题