【问题标题】:Cache POST requests with OkHttp使用 OkHttp 缓存 POST 请求
【发布时间】:2015-12-20 01:32:43
【问题描述】:

我使用 OkHttp 向我的服务器发出一些 POST 请求。这工作正常。 现在我想使用 OkHttp 的缓存来缓存请求的响应,并在设备离线时使用它们。 我尝试了许多其他问题的解决方案,但都没有奏效。

我使用 OkHttp 2.5.0

使用下面的代码,当设备可以访问互联网时,我会得到有效的响应。 但是如果我关闭互联网,它会抛出 java.net.UnknownHostException: Unable to resolve host "example.com": No address associated with hostname

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

重写缓存头的拦截器:

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

【问题讨论】:

    标签: android caching okhttp


    【解决方案1】:

    你不能用 OkHttp 的缓存来缓存 POST 请求。您需要使用其他机制来存储它们。

    【讨论】:

    • ...或使用 GET 请求。
    • 你能给我看看这方面的任何文件或官方说明吗?
    • @JesseWilson 是对的,这里有指向忽略任何其他不是 GET 的动词的代码的链接:okhttp3/Cache.java#L230
    • 除了 OkHttp 之外,还有什么方法可以缓存 POST 请求但不删除 Retrofit 实现?
    猜你喜欢
    • 2015-01-02
    • 2014-06-20
    • 1970-01-01
    • 2023-03-03
    • 2014-11-25
    • 2012-02-19
    • 2016-12-26
    • 2014-06-17
    • 1970-01-01
    相关资源
    最近更新 更多