Search in sources :

Example 46 with CacheControl

use of okhttp3.CacheControl in project BaseProject by fly803.

the class CacheInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    if (!NetworkUtils.isConnected()) {
        // 无网络下强制使用缓存,无论缓存是否过期,此时该请求实际上不会被发送出去。
        request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
    }
    okhttp3.Response response = chain.proceed(request);
    if (NetworkUtils.isConnected()) {
        // 有网络情况下,根据请求接口的设置,配置缓存。
        // 这样在下次请求时,根据缓存决定是否真正发出请求。
        String cacheControl = request.cacheControl().toString();
        // 当然如果你想在有网络的情况下都直接走网络,那么只需要
        // 将其超时时间这是为0即可:String cacheControl="Cache-Control:public,max-age=0"
        // read from cache for 1 minute
        int maxAge = 60 * 60;
        return response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge).removeHeader("Pragma").build();
    } else {
        // 无网络
        // tolerate 4-weeks stale
        int maxStale = 60 * 60 * 24 * 28;
        return response.newBuilder().header("Cache-Control", "public,only-if-cached,max-stale=" + maxStale).removeHeader("Pragma").build();
    }
}
Also used : Request(okhttp3.Request) Response(okhttp3.Response)

Aggregations

Request (okhttp3.Request)34 Response (okhttp3.Response)29 CacheControl (okhttp3.CacheControl)16 IOException (java.io.IOException)12 File (java.io.File)10 Interceptor (okhttp3.Interceptor)9 Cache (okhttp3.Cache)8 OkHttpClient (okhttp3.OkHttpClient)6 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)6 Provides (dagger.Provides)4 Singleton (javax.inject.Singleton)4 Call (okhttp3.Call)4 RequestBody (okhttp3.RequestBody)4 Uri (android.net.Uri)3 Map (java.util.Map)3 AsyncTask (android.os.AsyncTask)2 ContentLengthInputStream (com.bumptech.glide.util.ContentLengthInputStream)2 StethoInterceptor (com.facebook.stetho.okhttp3.StethoInterceptor)2 ProgressRequestBody (io.chelizi.amokhttp.upload.ProgressRequestBody)2 FileOutputStream (java.io.FileOutputStream)2