gpt4 book ai didi

android - 无法从缓存 okHttp 和改造中加载数据

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:07:57 26 4
gpt4 key购买 nike

这是我调用 api 的代码,还通过改造为 okhttp 定义了缓存:

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);
}
}
}

现在从我的主要 Activity 中我调用这个演示类:

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

现在,当我通过 Internet 连接运行此 Activity 时,它工作正常,但当我断开 Internet 连接并再次运行此 Activity 时,它不会从缓存中加载数据。

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

最佳答案

你可以试试这个:

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;
}
}

对我来说效果很好。

关于android - 无法从缓存 okHttp 和改造中加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45278774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com