Okhttp 在使用 Etags 时不 return 缓存响应
Okhttp doesn't return cached response when using Etags
我有一个简单的用例,其中服务器 return 为请求提供了 Etag,并且该 etag 添加为 header(即 If-None-Match
) 所有后续 url 请求。如果响应发生变化,服务器可以用 200
响应,否则用 304
响应。对于后者,重用来自缓存的响应是有意义的。但是 okhttp 总是 returns null
作为缓存的响应。
我进行了一些故障排除,响应由 okhttp 在内部写入磁盘,但 CachingStrategy
不会 return 写入 CacheInterceptor
。仔细查看 CachingStrategy
class,有 documentation specifically 声明不会使用缓存:
/**
* Returns true if the request contains conditions that save the server from sending a response
* that the client has locally. When a request is enqueued with its own conditions, the built-in
* response cache won't be used.
*/
private fun hasConditions(request: Request): Boolean =
request.header("If-Modified-Since") != null || request.header("If-None-Match") != null
}
有没有办法解决此问题并改用缓存的响应?
(我按照描述启用了缓存 here 并且我使用的是 okhttp 版本 3.10.0
)
此外,奇怪的是我不得不手动添加 Etag。 Okhttp 无法自行将 etag 添加到后续请求。
编辑 - 更正,Okhttp 正确添加了 etag header。我需要使用网络拦截器与常规拦截器来查看 etag header 被添加到后续请求
与这些问题有些相关:
要么你自己做缓存,要么让 OkHttp 的缓存做缓存。当您添加自己的条件时,OkHttp 假设您想要完全控制缓存,但它不会参与其中。
我有一个简单的用例,其中服务器 return 为请求提供了 Etag,并且该 etag 添加为 header(即 If-None-Match
) 所有后续 url 请求。如果响应发生变化,服务器可以用 200
响应,否则用 304
响应。对于后者,重用来自缓存的响应是有意义的。但是 okhttp 总是 returns null
作为缓存的响应。
我进行了一些故障排除,响应由 okhttp 在内部写入磁盘,但 CachingStrategy
不会 return 写入 CacheInterceptor
。仔细查看 CachingStrategy
class,有 documentation specifically 声明不会使用缓存:
/**
* Returns true if the request contains conditions that save the server from sending a response
* that the client has locally. When a request is enqueued with its own conditions, the built-in
* response cache won't be used.
*/
private fun hasConditions(request: Request): Boolean =
request.header("If-Modified-Since") != null || request.header("If-None-Match") != null
}
有没有办法解决此问题并改用缓存的响应?
(我按照描述启用了缓存 here 并且我使用的是 okhttp 版本 3.10.0
)
此外,奇怪的是我不得不手动添加 Etag。 Okhttp 无法自行将 etag 添加到后续请求。
编辑 - 更正,Okhttp 正确添加了 etag header。我需要使用网络拦截器与常规拦截器来查看 etag header 被添加到后续请求
与这些问题有些相关:
要么你自己做缓存,要么让 OkHttp 的缓存做缓存。当您添加自己的条件时,OkHttp 假设您想要完全控制缓存,但它不会参与其中。