Cache POST requests with OkHttp

2019-04-30 23:07发布

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();

1条回答
Viruses.
2楼-- · 2019-04-30 23:26

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

查看更多
登录 后发表回答