gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:03:52 25 4
gpt4 key购买 nike

我有以下方法从 wiktionary.org 请求页面,问题是服务器在 header 中返回 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 来重写缓存控制。

关于java - 如何在 Android 上使用 HttpsURLConnection 和 HttpResponseCache 强制缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47915537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com