Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

android - Caching Images and strings using Retrofit, okhttp and picasso

I'm trying to optimize this code for caching purpose . this code made the cache only for 1 day before it reconnect to internet again to make new cache . I wants to make it for 60 days before it access again to network make new cache . also there is slow down on images which is coming from cache using picasso picasso:2.5.2 retrofit2:retrofit:2.7.2 retrofit2:converter-gson:2.7.2 okhttp3:okhttp:4.4.1 okhttp3:logging-interceptor:4.4.1

     if (retrofit==null) {
         OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                 .addInterceptor( provideHttpLoggingInterceptor() )
                 .addInterceptor( provideOfflineCacheInterceptor() )
                 .addNetworkInterceptor( provideCacheInterceptor() )
                 .cache( provideCache() )
                 .connectTimeout(60, TimeUnit.SECONDS)
                 .readTimeout(60, TimeUnit.SECONDS)
                 .writeTimeout(60, TimeUnit.SECONDS)
                 .build();

         OkHttp3Downloader okHttp3Downloader = new OkHttp3Downloader(okHttpClient);
         Picasso picasso = new Picasso.Builder(MyApplication.getInstance())
                 .downloader(okHttp3Downloader)
                 .build();


         Picasso.setSingletonInstance(picasso);

         retrofit = new Retrofit.Builder()
                 .baseUrl(Global.API_URL)
                 .client(okHttpClient)
                 .addConverterFactory(GsonConverterFactory.create())
                 .build();
     }
     return retrofit;
 }
 private static Cache provideCache ()
 {
     Cache cache = null;
     try
     {
         cache = new Cache( new File(MyApplication.getInstance().getCacheDir(), "wallpaper-cache" ),
                 100 * 1024 * 1024 ); // 100 MB
     }
     catch (Exception e)
     {
         Timber.e( e, "Could not create Cache!" );
     }
     return cache;
 }
 private static HttpLoggingInterceptor provideHttpLoggingInterceptor ()
 {
     HttpLoggingInterceptor httpLoggingInterceptor =
             new HttpLoggingInterceptor( new HttpLoggingInterceptor.Logger()
             {
                 @Override
                 public void log (String message)
                 {
                     Timber.d( message );
                     Log.v("MYAPI",message);

                 }
             } );
     httpLoggingInterceptor.setLevel( BuildConfig.DEBUG ? HEADERS : NONE );
     return httpLoggingInterceptor;
 }
 public static Interceptor provideCacheInterceptor ()
 {
     return new Interceptor()
     {
         @Override
         public Response intercept (Chain chain) throws IOException
         {
             Response response = chain.proceed( chain.request() );
             int maxAge = 60  * 60; // read from cache
             return response.newBuilder()
                     .header( CACHE_CONTROL, "public, max-age=" + maxAge)
                     .removeHeader("Pragma")
                     .build();
         }
     };
 }
 public static Interceptor provideOfflineCacheInterceptor ()
 {
     return new Interceptor()
     {

         @Override
         public Response intercept (Chain chain) throws IOException
         {
             Request request = chain.request();
             if ( !MyApplication.hasNetwork() )
             {
                 int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
                 request = request.newBuilder()
                         .header( CACHE_CONTROL,  "public, only-if-cached, max-stale=" + maxStale)
                         .removeHeader("Pragma")
                         .build();
             }
             return chain.proceed( request );
         }
     };
 }

} ```



 
question from:https://stackoverflow.com/questions/65909069/caching-images-and-strings-using-retrofit-okhttp-and-picasso

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can rewrite the cache headers in an interceptor like this example How to cache okHTTP response from Web server

public class CacheInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = chain.proceed(chain.request());

        CacheControl cacheControl = new CacheControl.Builder()
                .maxAge(15, TimeUnit.MINUTES) // 15 minutes cache
                .build();

        return response.newBuilder()
                .removeHeader("Pragma")
                .removeHeader("Cache-Control")
                .header("Cache-Control", cacheControl.toString())
                .build();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...