Android OkHttp和改装2缓存和脱机使用

Android OkHttp和改装2缓存和脱机使用,android,caching,retrofit,okhttp,Android,Caching,Retrofit,Okhttp,我想离线存储服务器响应 这是我的代码: public void loadJSON() { OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(4, TimeUnit.SECONDS) .readTimeout(4, TimeUnit.SECONDS) .writeTimeout(4, Time

我想离线存储服务器响应

这是我的代码:

        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();
    }
public void loadJSON(){
OkHttpClient客户端=新建OkHttpClient.Builder()
.connectTimeout(4,时间单位为秒)
.readTimeout(4,时间单位为秒)
.writeTimeout(4,时间单位。秒)
.build();
改装改装=新改装.Builder()
.baseUrl(Config.URL\u MAIN+sid+“/”)
.addConverterFactory(GsonConverterFactory.create())
.客户(客户)
.build();
RequestInterfacePlanGesamt request=reformation.create(RequestInterfacePlanGesamt.class);
Call Call=request.getJSON();
call.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
//布拉布拉
}
}
公共接口请求接口语言SAMT{
@标题({
“用户代理:android”
})
@获取(Config.GESAMT)
调用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();

为什么要使用两个库来缓存结果?只需使用one@PreetikaKaur好吧,如果只有一个会更容易些,没关系。但是如何缓存呢?嗯,我添加了这个代码,我开始活动,我的片段开始加载内容。然后我切换片段,关闭互联网,然后返回到我的第一个片段,但是没有o缓存内容…您可能需要确认您的服务器正在发送相应的缓存头及其响应。@JesseWilson好的,我有一个Windows服务器。IIS必须发送什么?