Search in sources :

Example 1 with CacheInterceptor

use of okhttp3.internal.cache.CacheInterceptor in project GeekNews by codeestX.

the class HttpModule method provideClient.

@Singleton
@Provides
OkHttpClient provideClient(OkHttpClient.Builder builder) {
    if (BuildConfig.DEBUG) {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
        builder.addInterceptor(loggingInterceptor);
    }
    File cacheFile = new File(Constants.PATH_CACHE);
    Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
    Interceptor cacheInterceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!SystemUtil.isNetworkConnected()) {
                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
            }
            Response response = chain.proceed(request);
            if (SystemUtil.isNetworkConnected()) {
                int maxAge = 0;
                // 有网络时, 不缓存, 最大保存时长为0
                response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge).removeHeader("Pragma").build();
            } else {
                // 无网络时,设置超时为4周
                int maxStale = 60 * 60 * 24 * 28;
                response.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).removeHeader("Pragma").build();
            }
            return response;
        }
    };
    //        Interceptor apikey = new Interceptor() {
    //            @Override
    //            public Response intercept(Chain chain) throws IOException {
    //                Request request = chain.request();
    //                request = request.newBuilder()
    //                        .addHeader("apikey",Constants.KEY_API)
    //                        .build();
    //                return chain.proceed(request);
    //            }
    //        }
    //        设置统一的请求头部参数
    //        builder.addInterceptor(apikey);
    //设置缓存
    builder.addNetworkInterceptor(cacheInterceptor);
    builder.addInterceptor(cacheInterceptor);
    builder.cache(cache);
    //设置超时
    builder.connectTimeout(10, TimeUnit.SECONDS);
    builder.readTimeout(20, TimeUnit.SECONDS);
    builder.writeTimeout(20, TimeUnit.SECONDS);
    //错误重连
    builder.retryOnConnectionFailure(true);
    return builder.build();
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) File(java.io.File) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Cache(okhttp3.Cache) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Example 2 with CacheInterceptor

use of okhttp3.internal.cache.CacheInterceptor in project Gradle-demo by Arisono.

the class RetrofitImpl method initClient.

@Override
public void initClient() {
    // 本类保证初始化一次,减少系统开销
    Builder okBuilder = new OkHttpClient.Builder().connectTimeout(mbuilder.getConnectTimeout(), TimeUnit.SECONDS).readTimeout(mbuilder.getReadTimeout(), TimeUnit.SECONDS).writeTimeout(mbuilder.getWriteTimeout(), TimeUnit.SECONDS).sslSocketFactory(OkhttpUtils.createSSLSocketFactory(), // 信任所有证书
    new TrustAllCerts()).hostnameVerifier(new TrustAllHostnameVerifier());
    LogInterceptor logInterceptor = new LogInterceptor();
    logInterceptor.setBuilder(mbuilder);
    okBuilder.addInterceptor(logInterceptor);
    if (mbuilder.getCacheFileSize() != 0) {
        okBuilder.cache(new Cache(mbuilder.getCacheFile(), mbuilder.getCacheFileSize()));
        okBuilder.addInterceptor(new CacheInterceptor(String.valueOf(mbuilder.getCacheTime()), mbuilder.getCacheType()));
    }
    //后期缓存策略改进
    switch(mbuilder.getCacheType()) {
        case CacheType.ONLY_NETWORK:
            OkhttpUtils.println("CacheType.ONLY_NETWORK");
            break;
        case CacheType.ONLY_CACHED:
            OkhttpUtils.println("CacheType.ONLY_CACHED");
            break;
        case CacheType.CACHED_ELSE_NETWORK:
            break;
        case CacheType.NETWORK_ELSE_CACHED:
            break;
        default:
            break;
    }
    OkHttpClient client = okBuilder.build();
    retrofit = new Retrofit.Builder().client(client).baseUrl(mbuilder.getBaseUrl()).addConverterFactory(StringConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
}
Also used : Builder(okhttp3.OkHttpClient.Builder) Retrofit(retrofit2.Retrofit) TrustAllHostnameVerifier(com.gradle.android.retrofit.OkhttpUtils.TrustAllHostnameVerifier) OkHttpClient(okhttp3.OkHttpClient) Builder(okhttp3.OkHttpClient.Builder) LogInterceptor(com.gradle.android.Interceptor.LogInterceptor) CacheInterceptor(com.gradle.android.Interceptor.CacheInterceptor) TrustAllCerts(com.gradle.android.retrofit.OkhttpUtils.TrustAllCerts) Cache(okhttp3.Cache)

Example 3 with CacheInterceptor

use of okhttp3.internal.cache.CacheInterceptor in project SeeWeather by xcc3641.

the class RetrofitSingleton method initOkHttp.

private static void initOkHttp() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    // 缓存 http://www.jianshu.com/p/93153b34310e
    File cacheFile = new File(C.NET_CACHE);
    Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
    Interceptor cacheInterceptor = chain -> {
        Request request = chain.request();
        if (!Util.isNetworkConnected(BaseApplication.getAppContext())) {
            request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
        }
        Response response = chain.proceed(request);
        Response.Builder newBuilder = response.newBuilder();
        if (Util.isNetworkConnected(BaseApplication.getAppContext())) {
            int maxAge = 0;
            // 有网络时 设置缓存超时时间0个小时
            newBuilder.header("Cache-Control", "public, max-age=" + maxAge);
        } else {
            // 无网络时,设置超时为4周
            int maxStale = 60 * 60 * 24 * 28;
            newBuilder.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale);
        }
        return newBuilder.build();
    };
    builder.cache(cache).addInterceptor(cacheInterceptor);
    if (BuildConfig.DEBUG) {
        builder.addNetworkInterceptor(new StethoInterceptor());
    }
    // 设置超时
    builder.connectTimeout(15, TimeUnit.SECONDS);
    builder.readTimeout(20, TimeUnit.SECONDS);
    builder.writeTimeout(20, TimeUnit.SECONDS);
    // 错误重连
    builder.retryOnConnectionFailure(true);
    sOkHttpClient = builder.build();
}
Also used : StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) Interceptor(okhttp3.Interceptor) Request(okhttp3.Request) Cache(okhttp3.Cache) BaseApplication(com.xiecc.seeWeather.base.BaseApplication) C(com.xiecc.seeWeather.common.C) CacheControl(okhttp3.CacheControl) Consumer(io.reactivex.functions.Consumer) CityORM(com.xiecc.seeWeather.modules.main.domain.CityORM) File(java.io.File) Retrofit(retrofit2.Retrofit) RxJava2CallAdapterFactory(retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory) BuildConfig(com.xiecc.seeWeather.BuildConfig) TimeUnit(java.util.concurrent.TimeUnit) ToastUtil(com.xiecc.seeWeather.common.utils.ToastUtil) OkHttpClient(okhttp3.OkHttpClient) Util(com.xiecc.seeWeather.common.utils.Util) RxUtil(com.xiecc.seeWeather.common.utils.RxUtil) GsonConverterFactory(retrofit2.converter.gson.GsonConverterFactory) Version(com.xiecc.seeWeather.modules.about.domain.Version) Response(okhttp3.Response) Observable(io.reactivex.Observable) WhereBuilder(com.litesuits.orm.db.assit.WhereBuilder) Weather(com.xiecc.seeWeather.modules.main.domain.Weather) Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) WhereBuilder(com.litesuits.orm.db.assit.WhereBuilder) Request(okhttp3.Request) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) File(java.io.File) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) Interceptor(okhttp3.Interceptor) Cache(okhttp3.Cache)

Example 4 with CacheInterceptor

use of okhttp3.internal.cache.CacheInterceptor in project okhttp by square.

the class RealCall method getResponseWithInterceptorChain.

Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
    interceptors.addAll(client.interceptors());
    interceptors.add(retryAndFollowUpInterceptor);
    interceptors.add(new BridgeInterceptor(client.cookieJar()));
    interceptors.add(new CacheInterceptor(client.internalCache()));
    interceptors.add(new ConnectInterceptor(client));
    if (!forWebSocket) {
        interceptors.addAll(client.networkInterceptors());
    }
    interceptors.add(new CallServerInterceptor(forWebSocket));
    Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0, originalRequest);
    return chain.proceed(originalRequest);
}
Also used : ConnectInterceptor(okhttp3.internal.connection.ConnectInterceptor) RealInterceptorChain(okhttp3.internal.http.RealInterceptorChain) ArrayList(java.util.ArrayList) CallServerInterceptor(okhttp3.internal.http.CallServerInterceptor) BridgeInterceptor(okhttp3.internal.http.BridgeInterceptor) CacheInterceptor(okhttp3.internal.cache.CacheInterceptor) ConnectInterceptor(okhttp3.internal.connection.ConnectInterceptor) RetryAndFollowUpInterceptor(okhttp3.internal.http.RetryAndFollowUpInterceptor) CallServerInterceptor(okhttp3.internal.http.CallServerInterceptor) BridgeInterceptor(okhttp3.internal.http.BridgeInterceptor) CacheInterceptor(okhttp3.internal.cache.CacheInterceptor)

Example 5 with CacheInterceptor

use of okhttp3.internal.cache.CacheInterceptor in project bilibili-android-client by HotBitmapGG.

the class RetrofitHelper method initOkHttpClient.

/**
   * 初始化OKHttpClient,设置缓存,设置超时时间,设置打印日志,设置UA拦截器
   */
private static void initOkHttpClient() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    if (mOkHttpClient == null) {
        synchronized (RetrofitHelper.class) {
            if (mOkHttpClient == null) {
                //设置Http缓存
                Cache cache = new Cache(new File(BilibiliApp.getInstance().getCacheDir(), "HttpCache"), 1024 * 1024 * 10);
                mOkHttpClient = new OkHttpClient.Builder().cache(cache).addInterceptor(interceptor).addNetworkInterceptor(new CacheInterceptor()).addNetworkInterceptor(new StethoInterceptor()).retryOnConnectionFailure(true).connectTimeout(30, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).addInterceptor(new UserAgentInterceptor()).build();
            }
        }
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) File(java.io.File) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Cache(okhttp3.Cache)

Aggregations

Cache (okhttp3.Cache)6 File (java.io.File)5 StethoInterceptor (com.facebook.stetho.okhttp3.StethoInterceptor)3 Provides (dagger.Provides)3 Singleton (javax.inject.Singleton)3 Interceptor (okhttp3.Interceptor)3 OkHttpClient (okhttp3.OkHttpClient)3 Request (okhttp3.Request)3 Response (okhttp3.Response)3 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)3 CacheControl (okhttp3.CacheControl)2 Retrofit (retrofit2.Retrofit)2 CacheInterceptor (com.gradle.android.Interceptor.CacheInterceptor)1 LogInterceptor (com.gradle.android.Interceptor.LogInterceptor)1 TrustAllCerts (com.gradle.android.retrofit.OkhttpUtils.TrustAllCerts)1 TrustAllHostnameVerifier (com.gradle.android.retrofit.OkhttpUtils.TrustAllHostnameVerifier)1 WhereBuilder (com.litesuits.orm.db.assit.WhereBuilder)1 DiskCache (com.ljy.devring.cache.support.DiskCache)1 MemoryCache (com.ljy.devring.cache.support.MemoryCache)1 SpCache (com.ljy.devring.cache.support.SpCache)1