gpt4 book ai didi

java - OkHttp 不缓存请求

转载 作者:行者123 更新时间:2023-11-30 02:36:37 27 4
gpt4 key购买 nike

由于某种原因,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}

最佳答案

OkHttp 将响应正文写入缓存,作为您读取正文的副作用。调用response.body().string()即可完成此操作,或者您也可以通过其他方式读取正文。

关于java - OkHttp 不缓存请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42877750/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com