在以下源代码中如何使用Retrofit Cache?

时间:2018-08-28 06:15:38

标签: android retrofit2

我无法使用翻新缓存。我已经在论坛上搜索了很多次,大多数结果都还可以,而且我能够找到它的概念,但是当我尝试在代码中实现时,却无法做到。请帮助我,因为我也是新手。一个星期,我尝试使用排球库,但高速缓存一切正常,但是排球发送了两个请求,并且我的数据显示了两次,我尝试了所有可能的方式,但不能用排球这样做,最后现在我转向了翻新,但是再次我被困住了,因为我不是计算机科学背景的人。请帮助我,我将感谢大家。我只想对以下这些代码使用改造。这些示例代码摘自https://github.com/prakashpun/RetrofitTutorial

RetrofitClientInstance.java

public class RetrofitClientInstance {

    private static Retrofit retrofit;
    private static final String BASE_URL = "https://jsonplaceholder.typicode.com";

    public static Retrofit getRetrofitInstance() {
        if (retrofit == null) {
            retrofit = new retrofit2.Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

GetDataService.java

public interface GetDataService {
@GET("/photos")
Call<List<RetroPhoto>> getAllPhotos();
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private CustomAdapter adapter;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GetDataService service = RetrofitClientInstance.getRetrofitInstance().create(GetDataService.class);

        Call<List<RetroPhoto>> call = service.getAllPhotos();
        call.enqueue(new Callback<List<RetroPhoto>>() {

            @Override
            public void onResponse(Call<List<RetroPhoto>> call, Response<List<RetroPhoto>> response) {

                generateDataList(response.body());
            }

            @Override
            public void onFailure(Call<List<RetroPhoto>> call, Throwable t) {
                progressDoalog.dismiss();
                Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void generateDataList(List<RetroPhoto> photoList) {
        recyclerView = findViewById(R.id.customRecyclerView);
        adapter = new CustomAdapter(this,photoList);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
    }

}

我将在上述代码中实现的这些部分的示例以及如何实现。

Cache cache = new Cache(getCacheDir(), cacheSize);

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .cache(cache)
            .addInterceptor(new Interceptor() {
                @Override
                public okhttp3.Response intercept(Interceptor.Chain chain)
                        throws IOException {
                    Request request = chain.request();
                    if (!isNetworkAvailable()) {
                        int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale \
                        request = request
                                .newBuilder()
                                .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                                .build();
                    }
                    return chain.proceed(request);
                }
            })
            .build();

4 个答案:

答案 0 :(得分:0)

public static Retrofit getRetrofitInstance() {

OkHttpClient okHttpClient = new OkHttpClient.Builder()  
        .cache(cache)
        .build();

        if (retrofit == null) {
            retrofit = new retrofit2.Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

答案 1 :(得分:0)

您可以通过okhttp中的拦截器使用缓存机制,
在这里,我找到了一个带有示例的最佳实施文档,它可能会对您有所帮助

https://medium.com/@tsaha.cse/advanced-retrofit2-part-1-network-error-handling-response-caching-77483cf68620

这是小代码段

public class AppliCationClass extends Application {

  public static final int DISK_CACHE_SIZE = 10 * 1024 * 1024; // 10 MB

  private OkHttpClient provideOkHttpClient() {
    OkHttpClient.Builder okhttpClientBuilder = new OkHttpClient.Builder();
    okhttpClientBuilder.cache(getCache());
    return okhttpClientBuilder.build();
  }

  public Cache getCache() {
      File cacheDir = new File(getCacheDir(), "cache");
      Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
      return cache;
  }
}

答案 2 :(得分:0)

对于某些云API的缓存可能有用,请参阅以下链接以获取更多信息。

https://futurestud.io/tutorials/retrofit-2-activate-response-caching-etag-last-modified

以下是步骤摘要

1)初始化缓存

int cacheSize = SIZE_MB * 1024 * 1024; // Size in mb
Cache cache = new Cache(getCacheDir(), cacheSize);

2)使用OkHttpClient缓存功能

OkHttpClient okHttpClient = new OkHttpClient.Builder()  
    .cache(cache)
    .build();

3)使用上述http客户端进行改造

Retrofit.Builder builder = new Retrofit.Builder()  
    .baseUrl("http://www.your_api_base_url.in/")
    .client(okHttpClient);

Retrofit retrofit = builder.build();  

我希望这会有所帮助。

答案 3 :(得分:0)

您可以参考此功能

  

int cacheSize = 10 * 1024 * 1024; // 10 MB
  缓存缓存=新缓存(getCacheDir(),cacheSize);

OkHttpClient okHttpClient =新的OkHttpClient.Builder()
        .cache(缓存)         .build();

Retrofit.Builder builder =新的Retrofit.Builder()
        .baseUrl(“ http://10.0.2.2:3000/”)         .client(okHttpClient)         .addConverterFactory(GsonConverterFactory.create());

改造改造= builder.build();