有没有适当的解释如何添加缓存和ETAG / If-None-Match支持到Retrofit OkHttp?
我正在努力在2个项目中添加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()));
}
}
然后使用FULL日志级别和自定义标签创建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秒钟.如果我暂停和恢复应用程序 – 相同的请求需要250ms,清楚地击中缓存.如果我完全关闭应用程序并重新启动 – 它再次需要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标题