如何在 Android 上使用 HttpsURLConnection 和 HttpResponseCache 强制缓存?

How to force caching with HttpsURLConnection and HttpResponseCache on Android?

我有下面的方法从 wiktionary.org 请求页面,问题是服务器在 headers 中返回 Cache-control => private, must-revalidate, max-age=0,这阻止了 HttpsURLConnection存储请求。

有没有办法强制缓存这些页面?

protected static synchronized String getUrlContent(String url) throws ApiException {
    if (sUserAgent == null) {
        throw new ApiException("User-Agent string must be prepared");
    }

    try {
        URL obj = new URL(url);
        HttpsURLConnection connection = (HttpsURLConnection) obj.openConnection();

        connection.setRequestMethod("GET");
        connection.setRequestProperty("User-Agent", sUserAgent);
        //connection.addRequestProperty("Cache-Control", "max-stale");
        //connection.addRequestProperty("Cache-Control", "public, max-age=3600");
        //connection.addRequestProperty("Cache-Control", "only-if-cached");

        int responseCode = connection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) { // success
            throw new ApiException("Invalid response from server: " + responseCode);
        }

        InputStream inputStream = connection.getInputStream();
        ByteArrayOutputStream content = new ByteArrayOutputStream();

        // Read response into a buffered stream
        int readBytes = 0;
        while ((readBytes = inputStream.read(sBuffer)) != -1) {
            content.write(sBuffer, 0, readBytes);
        }

        HttpResponseCache cache = HttpResponseCache.getInstalled();
        if (cache != null) {
            Log.w("!!!", "Cache hit count: " + cache.getHitCount());
            //connection.addRequestProperty("Cache-Control", "public, max-age=3600");
            Log.w("!!!", "Cache-Control: " + connection.getHeaderField("Cache-Control"));
            //cache.put(new URI(url), connection);
        }

        // Return result from buffered stream
        return new String(content.toByteArray());

    } catch (Exception e) {
        throw new ApiException("Problem communicating with API", e);
    }
}

更新:

仍然无法通过 okhttp interceptors

获得缓存命中
static private OkHttpClient client;
static private Cache cache;

public static OkHttpClient getClient() {
    if (client == null) {
        File cacheDirectory = new File(App.getInstance().getCacheDir().getAbsolutePath(), "HttpCache");
        cache = new Cache(cacheDirectory, 1024 * 1024);
        client = new OkHttpClient.Builder()
                .cache(cache)
                .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR).build();
    }
    return client;
}

/** Dangerous interceptor that rewrites the server's cache-control header. */
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
    @Override public Response intercept(Interceptor.Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        return originalResponse.newBuilder()
                .header("Cache-Control", "max-age=60")
                .build();
    }
};

protected static synchronized String getUrlContent(String url) throws ApiException {
    try {

        OkHttpClient httpClient = getClient();

        Request request = new Request.Builder()
                .url(url)
                .build();

        Response response = httpClient.newCall(request).execute();

        Log.w("!!!", "hitCount: " + cache.hitCount());

        return response.body().string();

    } catch (Exception e) {
        throw new ApiException("Problem communicating with API", e);
    }
}

请在初始化 OKHttpClient 时使用 addNetworkInterceptor 而不是 addInterceptor 来重写缓存控制。