Android OKHTTP 設定快取 斷網使用
阿新 • • 發佈:2019-02-01
OKHTTP 設定 GET 請求網路快取、快取時間以及斷網情況下的使用
- 基於 okhttp 3.9.1 測試
1. 設定本地本地快取的路徑、大小
public CacheResponse() {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
final String CACHE_PATH
= Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/okcache";
File cacheDirectory = new File(CACHE_PATH);
Cache cache = new Cache(cacheDirectory, cacheSize);
client = new OkHttpClient.Builder()
.cache(cache)
.build();
}
2. cacheControl 設定快取的最大時間
public void run() {
Request request = new Request.Builder()
.cacheControl(new CacheControl.Builder().maxStale(60 * 5, TimeUnit.SECONDS).build())
.url("http://publicobject.com/helloworld.txt")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "onFailure = " + e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseBody = response.body().string();
Log.e(TAG, " response = " + responseBody);
Log.e(TAG, " cache response: " + response.cacheResponse());
Log.e(TAG, " network response: " + response.networkResponse());
}
});
}
3. 測試結果如下:
1)第一次沒有快取:
2)第二次有快取:
3)再斷開手機網路:
4)在手機本地快取的檔案: