无法从okHttp&缓存加载数据翻新 [英] Not able to load data from cache okHttp & retrofit

查看:79
本文介绍了无法从okHttp&缓存加载数据翻新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在调用api的代码,还为翻新版的okhttp定义了缓存:

Here is my code where i am calling api and also define cache for okhttp with retrofit:

public class DemoPresenter {

    DemoView vDemoView;
    private Context mContext;

    public DemoPresenter(Context mcontext, DemoView vDemoView) {
        this.vDemoView = vDemoView;
        this.mContext = mcontext;
    }

    public void callAllProduct() {
        if (vDemoView != null) {
            vDemoView.showProductProgressBar();
        }


        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cache(new Cache(mContext.getCacheDir(), 10 * 1024 * 1024)) // 10 MB
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        if (BasicUtility.isInternet(mContext)) {
                            request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
                        } else {
                            request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
                        }
                        return chain.proceed(request);
                    }
                })
                .build();


        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("www.xyz.com/data/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();

        AllApi productApiService = retrofit.create(AllApi.class);
        Call<ProductData> call = productApiService.getProduct();

        try {
            call.enqueue(new Callback<ProductData>() {
                @Override
                public void onResponse(Call<ProductData> call, Response<ProductData> response) {
                    ArrayList<Product> alproducts = new ArrayList<>();
                    try {
                        alproducts = response.body().getProductData();
                        onSuccess(alproducts);
                    } catch (Exception e) {

                    }
                }
                @Override
                public void onFailure(Call<ProductData> call, Throwable t) {
                }
            });
        } catch (Exception e) {

        }
    }

    private void onSuccess(ArrayList<Product> alproducts) {
        if (vDemoView != null) {
            vDemoView.hideProductProgressBar();
            vDemoView.onProductSuccess(alproducts);
        }
    }
}

现在,从我的主要活动中,我将这个演讲者类称为:

Now from my main activity i am calling this presenter class:

DemoPresenter mDemoPresenter = new DemoPresenter(getApplicationContext(),this);
 mDemoPresenter.callAllProduct();

现在,当我通过Internet连接运行此活动时,它运行良好,但是当我断开Internet连接并再次运行此活动时,它将不会从缓存中加载数据.

Now when i run this activity with Internet connectivity then it works fine but when i disconnected internet and run this activity again then it wont load data from cache .

如果没有互联网,如何从缓存中加载此数据?

How can i load this data from cache if there is not internet ?

推荐答案

您可以尝试以下方法:

public class DemoPresenter {

    DemoView vDemoView;
    private Context mContext;
    private static final String CACHE_CONTROL = "Cache-Control";
    private static final String TAG = DemoPresenter.class.getName();

    public DemoPresenter(Context mcontext, DemoView vDemoView) {
        this.vDemoView = vDemoView;
        this.mContext = mcontext;
    }

    public void callAllProduct() {
        if (vDemoView != null) {
            vDemoView.showProductProgressBar();
        }


        OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor( provideOfflineCacheInterceptor() )
            .addNetworkInterceptor( provideCacheInterceptor() )
            .cache( provideCache() )
            .build();


       /* OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cache(new Cache(mContext.getCacheDir(), 10 * 1024 * 1024)) // 10 MB
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        if (BasicUtility.isInternet(mContext)) {
                            request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
                        } else {
                            request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
                        }
                        return chain.proceed(request);
                    }
                })
                .build();*/


        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("www.xyz.com/data/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();

        AllApi productApiService = retrofit.create(AllApi.class);
        Call<ProductData> call = productApiService.getProduct();

        try {
            call.enqueue(new Callback<ProductData>() {
                @Override
                public void onResponse(Call<ProductData> call, Response<ProductData> response) {
                    ArrayList<Product> alproducts = new ArrayList<>();
                    try {
                        alproducts = response.body().getProductData();
                        onSuccess(alproducts);
                    } catch (Exception e) {

                    }
                }
                @Override
                public void onFailure(Call<ProductData> call, Throwable t) {
                }
            });
        } catch (Exception e) {

        }
    }

    private void onSuccess(ArrayList<Product> alproducts) {
        if (vDemoView != null) {
            vDemoView.hideProductProgressBar();
            vDemoView.onProductSuccess(alproducts);
        }
    }

    public Interceptor provideOfflineCacheInterceptor () {
        return new Interceptor()
        {
            @Override
            public Response intercept (Chain chain) throws IOException
            {
                Request request = chain.request();

                if (BasicUtility.isInternet(mContext))
                {
                    CacheControl cacheControl = new CacheControl.Builder()
                        .maxStale( 7, TimeUnit.DAYS )
                        .build();

                    request = request.newBuilder()
                        .cacheControl( cacheControl )
                        .build();
                }

                return chain.proceed( request );
            }
        };
    }




    public static Interceptor provideCacheInterceptor ()
    {
        return new Interceptor()
        {
            @Override
            public Response intercept (Chain chain) throws IOException
            {
                Response response = chain.proceed( chain.request() );

                // re-write response header to force use of cache
                CacheControl cacheControl = new CacheControl.Builder()
                    .maxAge( 1, TimeUnit.MINUTES )
                    .build();

                return response.newBuilder()
                    .header( CACHE_CONTROL, cacheControl.toString() )
                    .build();
            }
        };
    }

    private Cache provideCache ()
    {
        Cache cache = null;
        try
        {
            cache = new Cache( new File( mContext.getCacheDir(), "http-cache" ),
                10 * 1024 * 1024 ); // 10 MB
        }
        catch (Exception e)
        {
            Log.e(TAG, "Could not create Cache!");
        }
        return cache;
    }
}

为我工作得很好.

这篇关于无法从okHttp&amp;缓存加载数据翻新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆