有关于Okhttp缓存拦截器的问题

我自定义了缓存拦截器,也设置了response的header,close了body,但还是无法将缓存数据写入到缓存文件中,就是三个缓存文件创建成功了,但只有两个文件有数据,分别是日志文件和response头文件,但数据文件就是空的,请问是什么原因啊?

网上的原因方法我都试了无效,在本机无效,在虚拟机也不行

    @Override
    public Response intercept(@SuppressWarnings("NullableProblems") Chain chain) throws IOException {
    
        Request request = chain.request();
        
        Response response = chain.proceed(request);
        
        response = response.newBuilder()
            .removeHeader("Pragma")
            .removeHeader("Cache-Control")
            .header("Cache-Control","public,max-age=" + 3600*24)
            .build();

        return response;
    final OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .addNetworkInterceptor(new CacheInterceptor(this))
        .cache(new Cache(new File(getExternalCacheDir(),"Okhttp"),1024*1024*10))
        .build();

    final Request request = new Request.Builder()
            .url("http://api.douban.com/v2/movie/top250")
            .build();

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
    
                Call call1 = okHttpClient.newCall(request);
    
                Response response1 = call1.execute();
                
                Log.d("MainActivity","body:"+response1.body().string());

                Log.d("MainActivity","cacheResponse:"+response1.cacheResponse());
    
                response1.body().close();
    
                Call call2 = okHttpClient.newCall(request);
    
                Response response2 = call2.execute();
                
                Log.d("MainActivity","body:"+response2.body().string());

                Log.d("MainActivity","cacheResponse:"+response2.cacheResponse());
                
                response2.body().close();
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

输出:

body:....

cacheResponse:null

body:....

cacheResponse:null

两次都是只有body有数据,缓存没数据,而且我查看了缓存文件也是空的,没写入数据

阅读 2.3k
1 个回答

response1.body()这个方法,好像就会把流读完,你尝试用这个方法的时候,就把数据存起来,而不是日志输出,因为调用后,流的指针就已经在末尾了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏