我有以下方法从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 Interpectors击中缓存
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
重写Cache-Control。