如何给 Retrofit+OkHttp 添加缓存和ETAG
/If-None-Match
支持的适当解释是什么?我正在努力为两个项目添加Etag
支持,开始怀疑可能与HTTP头有关,另一个项目已经正确设置了一切,但缓存仍然不能按预期工作。
以下是我的尝试结果。结果表明,在应用程序的同一实例中缓存似乎正在工作,但一旦重新启动 - 所有内容都会再次加载得很慢。
此外,在我的日志中,我没有看到请求中添加If-None-Match
,所以我认为服务器不知道ETag
并且仍然完全重新计算响应。
下面是一些代码示例:
public class RetrofitHttpClient extends UrlConnectionClient
{
private OkUrlFactory generateDefaultOkUrlFactory()
{
OkHttpClient client = new com.squareup.okhttp.OkHttpClient();
try
{
Cache responseCache = new Cache(baseContext.getCacheDir(), SIZE_OF_CACHE);
client.setCache(responseCache);
}
catch (Exception e)
{
Logger.log(this, e, "Unable to set http cache");
}
client.setConnectTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
client.setReadTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS);
return new OkUrlFactory(client);
}
private final OkUrlFactory factory;
public RetrofitHttpClient()
{
factory = generateDefaultOkUrlFactory();
}
@Override
protected HttpURLConnection openConnection(retrofit.client.Request request) throws IOException
{
return factory.open(new URL(request.getUrl()));
}
}
使用完整的日志级别和自定义标签创建Rest适配器:
restAdapter = new RestAdapter.Builder()
.setClient(new RetrofitHttpClient())
.setEndpoint(Config.BASE_URL)
.setRequestInterceptor(new SignatureSetter())
.setConverter(new JacksonConverter(JsonHelper.getObjectMapper()))
.setLogLevel(RestAdapter.LogLevel.FULL)
.setLog(new AndroidLog("=NETWORK="))
.build();
我在应用程序的第一个屏幕上有一个长请求供测试使用。 当我打开应用程序时,完成该请求需要7秒钟。如果我暂停并恢复应用程序-相同的请求只需要250毫秒,显然命中缓存。如果我完全关闭应用程序并重新启动-它再次需要7秒钟。
更新: 如建议所述,我已经使用自定义的Retrofit构建并附加了LoggingInterceptor。下面是我收到的内容。
Received response for *** in 449,3ms
Date: Wed, 07 Jan 2015 09:02:23 GMT
Server: Apache
X-Powered-By: PHP/5.4.31
Access-Control-Allow-Credentials: true
Pragma:
Cache-Control: public, max-age=3600
X-Frame-Options: SAMEORIGIN
Etag: "hLxLRYztkinJAB453nRV7ncBSuU=-gzip"
Last-Modified: Wed, 24 Dec 2014 13:09:04 GMT
Vary: Accept-Encoding
Content-Encoding: gzip
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
OkHttp-Selected-Protocol: http/1.1
OkHttp-Sent-Millis: 1420621288104
OkHttp-Received-Millis: 1420621288554
Sending request **** on Connection{****:80, proxy=DIRECT@ hostAddress=**** cipherSuite=none protocol=http/1.1}
Accept: application/json;
Host: ****
Connection: Keep-Alive
Accept-Encoding: gzip
User-Agent: okhttp/2.2.0
Response is equal to described above
正如您所看到的,下一个请求中没有出现If-None-Match
头。
close()
。) - Jesse Wilson