使用OkHttp缓存POST请求 [英] Cache POST requests with OkHttp

查看:337
本文介绍了使用OkHttp缓存POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用OkHttp向我的服务器发出一些POST请求.这很好. 现在,我想使用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.

我使用OkHttp 2.5.0

I use OkHttp 2.5.0

使用以下代码,当设备可以访问互联网时,我会收到一个有效的响应. 但是,如果我关闭Internet,则会抛出java.net.UnknownHostException:无法解析主机"example.com":没有与主机名关联的地址

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

这是我当前的代码,该代码不起作用:

用于重写缓存头的拦截器:

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

获取客户端的方法:

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;
}

提出请求:

RequestBody body = RequestBody.create(TEXT, data);
Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
Response response = getHttpClient().newCall(request).execute();

推荐答案

您无法使用OkHttp的缓存来缓存POST请求.您需要使用其他某种机制来存储它们.

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

这篇关于使用OkHttp缓存POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆