我正在尝试为OkHttp设置缓存,所以它只在第一次尝试从服务器检索响应时才向服务器请求,直到过期标头日期,或者来自服务器的缓存控制标头使响应无效从缓存.
目前,它缓存响应,但在再次请求资源时不使用它.可能这不是应该使用的方式.
我正在使用这样的缓存设置OkHttpClient:
public static Cache createHttpClientCache(Context context) {
try {
File cacheDir = context.getDir("service_api_cache", Context.MODE_PRIVATE);
return new Cache(cacheDir, HTTP_CACHE_SIZE);
} catch (IOException e) {
Log.e(TAG, "Couldn't create http cache because of IO problem.", e);
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
这是这样使用的:
if(cache == null) {
cache = createHttpClientCache(context);
}
sClient.setCache(cache);
Run Code Online (Sandbox Code Playgroud)
这就是我用OkHttp向服务器发出的一个请求,它实际上没有使用缓存:
public static JSONObject getApi(Context context)
throws IOException, JSONException, InvalidCookie {
HttpCookie sessionCookie = getServerSession(context);
if(sessionCookie == null){
throw new InvalidCookie();
}
String cookieStr = sessionCookie.getName()+"="+sessionCookie.getValue();
Request request = new Request.Builder() …Run Code Online (Sandbox Code Playgroud) 这是我的代码:
final HttpURLConnection conn = (HttpURLConnection) sourceURL.openConnection();
if (cachedPage != null) {
if (cachedPage.eTag != null) {
conn.setRequestProperty("If-None-Match", cachedPage.eTag);
}
conn.setIfModifiedSince(cachedPage.pageLastModified);
}
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
newCachedPage.eTag = conn.getHeaderField("ETag");
newCachedPage.pageLastModified = conn.getHeaderFieldDate("Last-Modified", 0);
} else if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
// Never reaches here
}
Run Code Online (Sandbox Code Playgroud)
我似乎永远不会得到HTTP_NOT_MODIFIED响应代码,甚至连续多次点击同一台服务器 - 页面肯定没有变化.此外,conn.getHeaderField("ETag")似乎总是响应null,有时conn.getHeaderFieldDate("Last-Modified",0)返回0.我已经尝试过针对各种Web服务器.
谁能告诉我我做错了什么?