[英]OkHttp and Retrofit 2 caching and offline usage
I want to store my server responses offline.我想离线存储我的服务器响应。
This is my code:这是我的代码:
public void loadJSON() {
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(4, TimeUnit.SECONDS)
.readTimeout(4, TimeUnit.SECONDS)
.writeTimeout(4, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Config.URL_MAIN + sid + "/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
RequestInterfacePlanGesamt request = retrofit.create(RequestInterfacePlanGesamt.class);
Call<JSONResponsePlanGesamt> call = request.getJSON();
call.enqueue(new Callback<JSONResponsePlanGesamt>() {
@Override
public void onResponse(Call<JSONResponsePlanGesamt> call, Response<JSONResponsePlanGesamt> response) {
//bla bla
}
}
public interface RequestInterfacePlanGesamt {
@Headers({
"User-Agent: android"
})
@GET(Config.GESAMT)
Call<JSONResponsePlanGesamt> getJSON();
}
How can I use the content offline?如何离线使用内容? I already read some articles about caching but I really don`t know how to achieve the offline usage of my content.
我已经阅读了一些关于缓存的文章,但我真的不知道如何实现我的内容的离线使用。
Just use the cache()
method in your OkHttpClient Builder:只需在 OkHttpClient Builder 中使用
cache()
方法:
private static final long CACHE_SIZE = 10 * 1024 * 1024; // 10 MB
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(4, TimeUnit.SECONDS)
.readTimeout(4, TimeUnit.SECONDS)
.writeTimeout(4, TimeUnit.SECONDS)
.cache(new Cache(getApplication().getCacheDir(), CACHE_SIZE))
.build();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.