OkHttp不会缓存请求

时间:2017-03-18 17:45:30

标签: java okhttp

由于某种原因,OkHttp response.cacheResponse()总是返回null,即使请求应该被缓存。在下面的代码中我向http://httpbin.org/cache/60提出两个请求,我希望,第二个请求将从缓存中获取。但从输出中可以看出它不是。

我错过了什么?

代码:

@Test
public void test2_okhttp() throws IOException {
    int cacheSize = 100 * 1024 * 1024; // 100 MiB
    File cacheDir = new File("/tmp/ok_cache");
    cacheDir.mkdirs();

    Cache cache = new Cache(cacheDir, cacheSize);

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

    String url = "http://httpbin.org/cache/60";

    for(int i = 0; i < 2; i++) {
        Request request = new Request.Builder()
                .url(url)
                .build();

        Response response = client.newCall(request).execute();

        System.out.println("response1.cacheResponse() = " + response.cacheResponse());
        System.out.println("response1.networkResponse() = " + response.networkResponse());
    }
}

输出:

response1.cacheResponse() = null
response1.networkResponse() = Response{protocol=http/1.1, code=200, message=OK, url=http://httpbin.org/cache/60}
response1.cacheResponse() = null
response1.networkResponse() = Response{protocol=http/1.1, code=200, message=OK, url=http://httpbin.org/cache/60}

1 个答案:

答案 0 :(得分:2)

OkHttp将响应主体写入缓存,作为您阅读正文的副作用。拨打response.body().string()即可,或者您可以通过其他方式阅读正文。