简体   繁体   English

OkHttp不缓存请求

[英]OkHttp doesn't cache requests

For some reason OkHttp response.cacheResponse() always returns null, even if request should be cached. 由于某种原因,即使应该缓存请求,OkHttp response.cacheResponse()始终返回null。 In following code I'm making two requests to http://httpbin.org/cache/60 and I would expect, that second request would be fetched from cache. 在下面的代码中,我向http://httpbin.org/cache/60发出了两个请求,我希望第二个请求将从缓存中获取。 But it is not, as can be seen from output. 但是,从输出可以看出,它不是。

What am I missing? 我想念什么?

Code: 码:

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

Output: 输出:

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}

OkHttp writes the response body to the cache as a side-effect of you reading the body. OkHttp将响应正文写入缓存中,作为您读取正文的副作用。 Calling response.body().string() will do it, or you can read the body in another way. 调用response.body().string()可以完成此操作,或者您可以通过其他方式读取正文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM