簡體   English   中英

OkHttp 和 Retrofit 2 緩存和離線使用

[英]OkHttp and Retrofit 2 caching and offline usage

我想離線存儲我的服務器響應。

這是我的代碼:

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

如何離線使用內容? 我已經閱讀了一些關於緩存的文章,但我真的不知道如何實現我的內容的離線使用。

只需在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM