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:
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.