Monday, 1 July 2019

Check and recover a cached file with okhttp3

I am using okhttp3 to make requests to the server, not using retrofit. My idea is to make a call and save the response in cache for 15 minutes. if during those 15 minutes, the request is made again, recover the cache response, after 15 minutes, request it again from the server.

This is my code:

public class Handler_JSON_get {

    public Handler_JSON_get() {

    }

    public String makeServiceCall(String url, JSONObject data) {
        final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

        Cache cache = new Cache(new File(Environment.getExternalStorageDirectory().getPath() + "/Android/data/MY_PACKAGE/", "cache"), 10 * 1024 * 1024);

        OkHttpClient okHttpClient;

            Log.i("2134","Usando caché");
             okHttpClient = new OkHttpClient.Builder()
                    .addNetworkInterceptor(provideCacheInterceptor())
                    .readTimeout(45, TimeUnit.SECONDS)
                    .protocols(Arrays.asList(Protocol.HTTP_1_1))
                    .addInterceptor(provideCacheInterceptor())
                    .cache(cache)
                    .build();

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        try {
            Response response = okHttpClient.newCall(request).execute();

            Log.i(TAG,"Response:"+response.code());

            return response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    Interceptor provideCacheInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Response response = chain.proceed(chain.request());
                CacheControl cacheControl = new CacheControl.Builder()
                        .maxAge(15, TimeUnit.MINUTES)
                        .build();

                return response.newBuilder()
                        .header("cache", cacheControl.toString())
                        .build();
            }
        };
    }
}

The problem is that he always makes the call to the server and I have many doubts.

okhttp3 is responsible for seeing if there is a cached response in the storage?

The call saves a journal file, is this the correct file?

What am I missing or what am I doing wrong?

I have seen that there are quite a few questions about it, but I can not make those answers compatible with my code.

I would sincerely appreciate the parts that are necessary in my code to function properly, I start to go crazy.

Thanks in advance.



from Check and recover a cached file with okhttp3

No comments:

Post a Comment