Home Java javaTutorial Can Retrofit with OKHttp Use Cached Data Offline?

Can Retrofit with OKHttp Use Cached Data Offline?

Nov 04, 2024 pm 08:01 PM

Can Retrofit with OKHttp Use Cached Data Offline?

Can Retrofit with OKHttp Use Cache Data When Offline?

This question explores the use of Retrofit and OKHttp to cache HTTP responses for offline access. The code provided in the question follows a common approach, but the inability to retrieve cached responses offline suggests some additional configurations are needed.

Edit for Retrofit 2.x

For Retrofit 2.x, the preferred method for offline caching involves using an OkHttp Interceptor.

  1. Create an Interceptor:

    <code class="java">private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
        @Override public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            if (Utils.isNetworkAvailable(context)) {
                int maxAge = 60; // read from cache for 1 minute
                return originalResponse.newBuilder()
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .build();
            } else {
                int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
                return originalResponse.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .build();
            }
        }
    };</code>
    Copy after login
  2. Setup client:

    <code class="java">OkHttpClient client = new OkHttpClient();
    client.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR);
    
    //setup cache
    File httpCacheDirectory = new File(context.getCacheDir(), "responses");
    int cacheSize = 10 * 1024 * 1024; // 10 MiB
    Cache cache = new Cache(httpCacheDirectory, cacheSize);
    
    //add cache to the client
    client.setCache(cache);</code>
    Copy after login
  3. Add client to retrofit

    <code class="java">Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build();</code>
    Copy after login

OKHttp 2.0.x (Original Answer)

In OKHttp 2.0.x, the setResponseCache method is now setCache:

<code class="java">File httpCacheDirectory = new File(context.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);
}</code>
Copy after login

Original Answer

The original answer emphasizes the need for a Cache-Control: public header in the server response for OkClient to access cached data offline.

Additionally, parameterized header configuration can be achieved using a RequestInterceptor:

<code class="java">RestAdapter.Builder builder= new RestAdapter.Builder()
   .setRequestInterceptor(new RequestInterceptor() {
        @Override
        public void intercept(RequestFacade request) {
            request.addHeader("Accept", "application/json;versions=1");
            if (MyApplicationUtils.isNetworkAvailable(context)) {
                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);
            }
        }
});</code>
Copy after login

The above is the detailed content of Can Retrofit with OKHttp Use Cached Data Offline?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)