使用OkHttp缓存POST请求

Aur*_*tic 6 android caching okhttp

我用OkHttp向我的服务器发出一些POST请求.这很好用.现在我想使用OkHttp的缓存来缓存请求的响应,并在设备脱机时使用它们.我从其他问题尝试了很多解决方案,但没有一个能起作用.

我使用OkHttp 2.5.0

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

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

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

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();
    }
};
Run Code Online (Sandbox Code Playgroud)

获取客户端的方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

提出要求:

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

Jes*_*son 11

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

  • @JesseWilson是对的,在这里你有代码的链接,忽略任何其他动词,它不是GET:[okhttp3/Cache.java#L230](https://github.com/square/okhttp/blob/master/ okhttp/SRC /主/爪哇/ okhttp3/Cache.java#L230]) (2认同)
  • 除了OkHttp以外,还有什么方法可以缓存`POST`请求​​,但不能删除Retrofit实现? (2认同)
  • 这在 2022 年仍然如此:[okhttp3/Cache.kt](https://github.com/square/okhttp/blob/1ed8308feae1cf2f61950a993aa43116f2a50fc7/okhttp/src/jvmMain/kotlin/okhttp3/Cache.kt#L210) (2认同)