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

问题描述 投票:1回答:1

我有以下方法从wiktionary.org请求页面,问题是服务器在标头中返回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);
    }
}
java android httpsurlconnection httpresponsecache
1个回答
2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.