search

Home  >  Q&A  >  body text

android - OkHttp3.0是怎么写缓存和读缓存?

最近学习了OkHttp3.0
1、怎么把数据写入缓存?
2、怎么从缓存中读取数据?

PHP中文网PHP中文网2772 days ago440

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-17 17:36:32

    Reference here

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 17:36:32

      private final OkHttpClient client;
    
      public CacheResponse(File cacheDirectory) throws Exception {
        int cacheSize = 10 * 1024 * 1024; // 10 MiB
        Cache cache = new Cache(cacheDirectory, cacheSize);
    
        client = new OkHttpClient.Builder()
            .cache(cache)
            .build();
      }
    
      public void run() throws Exception {
        Request request = new Request.Builder()
            .url("http://publicobject.com/helloworld.txt")
            .build();
    
        Response response1 = client.newCall(request).execute();
        if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1);
    
        String response1Body = response1.body().string();
        System.out.println("Response 1 response:          " + response1);
        System.out.println("Response 1 cache response:    " + response1.cacheResponse());
        System.out.println("Response 1 network response:  " + response1.networkResponse());
    
        Response response2 = client.newCall(request).execute();
        if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2);
    
        String response2Body = response2.body().string();
        System.out.println("Response 2 response:          " + response2);
        System.out.println("Response 2 cache response:    " + response2.cacheResponse());
        System.out.println("Response 2 network response:  " + response2.networkResponse());
    
        System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body));
      }

    reply
    0
  • Cancelreply