Home | History | Annotate | Download | only in recipes
      1 /*
      2  * Copyright (C) 2014 Square, Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 package com.squareup.okhttp.recipes;
     17 
     18 import com.squareup.okhttp.Cache;
     19 import com.squareup.okhttp.OkHttpClient;
     20 import com.squareup.okhttp.Request;
     21 import com.squareup.okhttp.Response;
     22 import java.io.File;
     23 import java.io.IOException;
     24 
     25 public final class CacheResponse {
     26   private final OkHttpClient client;
     27 
     28   public CacheResponse(File cacheDirectory) throws Exception {
     29     int cacheSize = 10 * 1024 * 1024; // 10 MiB
     30     Cache cache = new Cache(cacheDirectory, cacheSize);
     31 
     32     client = new OkHttpClient();
     33     client.setCache(cache);
     34   }
     35 
     36   public void run() throws Exception {
     37     Request request = new Request.Builder()
     38         .url("http://publicobject.com/helloworld.txt")
     39         .build();
     40 
     41     Response response1 = client.newCall(request).execute();
     42     if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1);
     43 
     44     String response1Body = response1.body().string();
     45     System.out.println("Response 1 response:          " + response1);
     46     System.out.println("Response 1 cache response:    " + response1.cacheResponse());
     47     System.out.println("Response 1 network response:  " + response1.networkResponse());
     48 
     49     Response response2 = client.newCall(request).execute();
     50     if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2);
     51 
     52     String response2Body = response2.body().string();
     53     System.out.println("Response 2 response:          " + response2);
     54     System.out.println("Response 2 cache response:    " + response2.cacheResponse());
     55     System.out.println("Response 2 network response:  " + response2.networkResponse());
     56 
     57     System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body));
     58   }
     59 
     60   public static void main(String... args) throws Exception {
     61     new CacheResponse(new File("CacheResponse.tmp")).run();
     62   }
     63 }
     64