如何获取OkHttp响应码304的数据?

jul*_*jul 3 android caching okhttp

我读到代码为 304(未修改)的响应不应包含正文。那么,OkHttp 是否从缓存中获取正文,还是我们应该显式获取它,即

if reponseCode == 304:
      body = <getDataFromCache>
Run Code Online (Sandbox Code Playgroud)

对于后一种情况,如何从缓存中获取数据呢?

OkHttpClient client = new OkHttpClient();

File cacheDirectory = new File(context.getCacheDir(), "responses");

Cache cache = null;
try {
    cache = new Cache(cacheDirectory, 10 * 1024 * 1024); // 10M
    client.setCache(cache);
} catch (IOException e) {
    Log.e("AbstractFeedIntentService", "Could not create http cache", e);
}

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

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

// if code==304, does the response contain the data from the cache. If not, how to get it?
Run Code Online (Sandbox Code Playgroud)

Jes*_*son 5

OkHttp将从其响应缓存中返回数据。