How to use OkHttp's ETag and If-None-Match on android

1.8k views Asked by At

I use OkHttpClient (v3.0.1) which is in my application,but ETag and If-None-Match are not working。

For example:

First GET http://112.4.19.67/task/imags_avatar/20130607165126605.png

In Response, I get ETag and Last-Modified.

Request:

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

Response:

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

Second GET the same url : http://112.4.19.67/task/imags_avatar/20130607165126605.png

I think that I could see the If-None-Match in request. but it doesn't exist.

Request:

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

Response:

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

My Code

    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();

Thanks in advance for any help.

1

There are 1 answers

0
Jesse Wilson On

Are you reading the complete response body from the first request? OkHttp doesn't write the response to the cache until you finish reading the body.