如何在android上使用OkHttp的ETag和If-None-Match

时间:2016-02-05 07:24:27

标签: android okhttp etag last-modified if-none-match

我使用的是我的应用程序中的OkHttpClient(v3.0.1),但ETag和If-None-Match不起作用。

例如:

首先获取http://112.4.19.67/task/imags_avatar/20130607165126605.png

在回复中,我获得ETag和Last-Modified。

请求:

GET /task/imags_avatar/20130607165126605.png HTTP/1.1
Host: 112.4.19.67
Connection: Keep-Alive
Accept-Encoding: gzip
User-Agent: okhttp/3.0.1

响应:

HTTP/1.1 200 OK
Server: Apache
Last-Modified: Mon, 30 Jun 2014 04:44:43 GMT
ETag: "1205-4fd06515d9572"
Content-Type: image/png
Content-Length: 4613
Accept-Ranges: bytes
Date: Thu, 04 Feb 2016 13:30:05 GMT
X-Varnish: 3684240013 3683622711
Age: 1313
Via: 1.1 varnish
Connection: keep-alive

第二次获取相同的网址:http://112.4.19.67/task/imags_avatar/20130607165126605.png

我认为我可以在请求中看到If-None-Match。但它并不存在。

请求:

GET /task/imags_avatar/20130607165126605.png HTTP/1.1
Host: 112.4.19.67
Connection: Keep-Alive
Accept-Encoding: gzip
User-Agent: okhttp/3.0.1

响应:

HTTP/1.1 200 OK
Server: Apache
Last-Modified: Mon, 30 Jun 2014 04:44:43 GMT
ETag: "1205-4fd06515504c0"
Content-Type: image/png
Content-Length: 4613
Accept-Ranges: bytes
Date: Thu, 04 Feb 2016 13:30:26 GMT
X-Varnish: 3389168698 3388862573
Age: 642
Via: 1.1 varnish
Connection: keep-alive

我的代码

    File file = getCacheDir();
    Cache cache = new Cache(file, CACHE_SIZE);

    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.cache(cache);
    OkHttpClient client = builder.build();

    Request request = new Request.Builder()
            .url(url)
            .build();

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您是否正在阅读第一个请求中的完整回复正文?在您读完正文之前,OkHttp不会将响应写入缓存。