Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache POST requests with OkHttp

I make some POST requests to my server with OkHttp. This works fine. Now I want use the cache of OkHttp to cache the responses of the requests and use them when the device is offline. I tried many solutions from other questions, but none of them work.

I use OkHttp 2.5.0

With the code below, I get a valid response, when the device has internet access. But if I turn the internet off, it throws a java.net.UnknownHostException: Unable to resolve host "example.com": No address associated with hostname

Here is my current code, which does not work:

Interceptor for rewriting the cache headers:

private final Interceptor mCacheControlInterceptor = new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        if (isOnline()) {
            request.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=7887")
                    .build();
        } else {
            request.newBuilder()
                    .header("Cache-Control", "public, max-stale=2419200")
                    .build();
        }

        Response response = chain.proceed(request);

        // Re-write response CC header to force use of cache
        return response.newBuilder()
                .header("Cache-Control", "public, max-age=86400") // 1 day
                .build();
    }
};

Method to get the client:

private OkHttpClient getHttpClient() {
    if (mHttpClient == null) {
        mHttpClient = new OkHttpClient();
        mHttpClient.setConnectTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS);

        File cacheDir = mContext.getDir(CACHE_NAME, Context.MODE_PRIVATE);
        mHttpClient.setCache(new Cache(cacheDir, CACHE_SIZE));

        mHttpClient.networkInterceptors().add(mCacheControlInterceptor);
    }

    return mHttpClient;
}

Make the request:

RequestBody body = RequestBody.create(TEXT, data);
Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
Response response = getHttpClient().newCall(request).execute();
like image 557
Auroratic Avatar asked Sep 22 '15 21:09

Auroratic


1 Answers

You can't cache POST requests with OkHttp’s cache. You’ll need to store them using some other mechanism.

like image 190
Jesse Wilson Avatar answered Sep 30 '22 13:09

Jesse Wilson