Skip to content

Instantly share code, notes, and snippets.

@markshiz
Forked from swankjesse/RetrofitCachingExample.java
Last active May 5, 2018 02:34
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save markshiz/5cfe5546c5ec5cfbd309 to your computer and use it in GitHub Desktop.
Save markshiz/5cfe5546c5ec5cfbd309 to your computer and use it in GitHub Desktop.
Demonstrate HTTP caching with OkHttp 2.5.0 and Retrofit 1.9.0.
/*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.transloc.android;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import java.io.File;
import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowLog;
import retrofit.RestAdapter;
import retrofit.android.AndroidLog;
import retrofit.client.OkClient;
import retrofit.http.GET;
import retrofit.http.Path;
import static junit.framework.Assert.assertEquals;
@RunWith(RobolectricTestRunner.class)
@Config(manifest=Config.NONE)
public class CacheTest {
interface SodaService {
@GET("/{brand}") Object cola(@Path("brand") String brand);
}
@Before public void setUp() throws Exception {
ShadowLog.stream = System.out;
}
@Test public void testWhenCacheThenSuccess() throws Exception {
MockWebServer mockWebServer = new MockWebServer();
mockWebServer.start();
// Create an HTTP client that uses a cache on the file system. Android applications should use
// their Context to get a cache directory.
OkHttpClient okHttpClient = new OkHttpClient();
File cacheDir = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
Cache cache = new Cache(cacheDir, 1024);
okHttpClient.setCache(cache);
// Create a Retrofit RestAdapter for our SodaService interface.
Executor executor = Executors.newCachedThreadPool();
RestAdapter restAdapter = new RestAdapter.Builder()
.setExecutors(executor, executor)
.setClient(new OkClient(okHttpClient))
.setEndpoint(mockWebServer.url("/").toString())
.setLog(new AndroidLog("SodaService"))
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
SodaService sodaService = restAdapter.create(SodaService.class);
// /pepsi hits the web server and returns a response that will be fully cached for 60 seconds.
mockWebServer.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60")
.setBody("\"You got the right one, baby\""));
assertEquals(sodaService.cola("pepsi"), "You got the right one, baby");
assertEquals(cache.getRequestCount(), 1);
assertEquals(cache.getNetworkCount(), 1);
assertEquals(cache.getHitCount(), 0);
// /coke hits the web server and returns a response that will be conditionally cached.
mockWebServer.enqueue(new MockResponse().addHeader("ETag: v1").setBody("\"Always Coca-Cola\""));
assertEquals(sodaService.cola("coke"), "Always Coca-Cola");
assertEquals(cache.getRequestCount(), 2);
assertEquals(cache.getNetworkCount(), 2);
assertEquals(cache.getHitCount(), 0);
// /pepsi returns a response from the cache.
assertEquals(sodaService.cola("pepsi"), "You got the right one, baby");
assertEquals(cache.getRequestCount(), 3);
assertEquals(cache.getNetworkCount(), 2);
assertEquals(cache.getHitCount(), 1);
// /coke validates the cached response. The server says the cached version is still good.
mockWebServer.enqueue(new MockResponse().setResponseCode(304));
assertEquals(sodaService.cola("coke"), "Always Coca-Cola");
assertEquals(cache.getRequestCount(), 4);
assertEquals(cache.getNetworkCount(), 3);
assertEquals(cache.getHitCount(), 2);
mockWebServer.shutdown();
}
}
@markshiz
Copy link
Author

markshiz commented Oct 5, 2015

Log.FULL output is listed below. Notice the response code is listed incorrectly as 200 for the second 'coke' request. Also the Etag is missing from the second 'coke' request.

Oct 05, 2015 4:43:31 PM com.squareup.okhttp.mockwebserver.MockWebServer$3 execute
INFO: MockWebServer[53924] starting to accept connections
D/SodaService: ---> HTTP GET http://localhost:53924/pepsi
D/SodaService: ---> END HTTP (no body)
Oct 05, 2015 4:43:32 PM com.squareup.okhttp.mockwebserver.MockWebServer$4 processOneRequest
INFO: MockWebServer[53924] received request: GET /pepsi HTTP/1.1 and responded: HTTP/1.1 200 OK
D/SodaService: <--- HTTP 200 http://localhost:53924/pepsi (222ms)
D/SodaService: Cache-Control: max-age=60
D/SodaService: Content-Length: 29
D/SodaService: OkHttp-Selected-Protocol: http/1.1
D/SodaService: OkHttp-Sent-Millis: 1444077812299
D/SodaService: OkHttp-Received-Millis: 1444077812305
D/SodaService: "You got the right one, baby"
D/SodaService: <--- END HTTP (29-byte body)
D/SodaService: ---> HTTP GET http://localhost:53924/coke
D/SodaService: ---> END HTTP (no body)
D/SodaService: <--- HTTP 200 http://localhost:53924/coke (1ms)
Oct 05, 2015 4:43:32 PM com.squareup.okhttp.mockwebserver.MockWebServer$4 processOneRequest
D/SodaService: ETag: v1
D/SodaService: Content-Length: 18
INFO: MockWebServer[53924] received request: GET /coke HTTP/1.1 and responded: HTTP/1.1 200 OK
D/SodaService: OkHttp-Selected-Protocol: http/1.1
D/SodaService: OkHttp-Sent-Millis: 1444077812329
D/SodaService: OkHttp-Received-Millis: 1444077812329
D/SodaService: "Always Coca-Cola"
D/SodaService: <--- END HTTP (18-byte body)
D/SodaService: ---> HTTP GET http://localhost:53924/pepsi
D/SodaService: ---> END HTTP (no body)
D/SodaService: <--- HTTP 200 http://localhost:53924/pepsi (2ms)
D/SodaService: Cache-Control: max-age=60
D/SodaService: Content-Length: 29
D/SodaService: OkHttp-Selected-Protocol: http/1.1
D/SodaService: OkHttp-Sent-Millis: 1444077812299
D/SodaService: OkHttp-Received-Millis: 1444077812305
D/SodaService: "You got the right one, baby"
D/SodaService: <--- END HTTP (29-byte body)
D/SodaService: ---> HTTP GET http://localhost:53924/coke
D/SodaService: ---> END HTTP (no body)
D/SodaService: <--- HTTP 200 http://localhost:53924/coke (1ms)
D/SodaService: ETag: v1
D/SodaService: OkHttp-Selected-Protocol: http/1.1
D/SodaService: OkHttp-Sent-Millis: 1444077812337
D/SodaService: OkHttp-Received-Millis: 1444077812337
D/SodaService: "Always Coca-Cola"
D/SodaService: <--- END HTTP (18-byte body)
Oct 05, 2015 4:43:32 PM com.squareup.okhttp.mockwebserver.MockWebServer$4 processOneRequest
INFO: MockWebServer[53924] received request: GET /coke HTTP/1.1 and responded: HTTP/1.1 304 OK
Oct 05, 2015 4:43:32 PM com.squareup.okhttp.mockwebserver.MockWebServer$3 acceptConnections
INFO: MockWebServer[53924] done accepting connections: Socket closed

Process finished with exit code 0

@markshiz
Copy link
Author

markshiz commented Oct 6, 2015

See this tweet for explanation: https://twitter.com/JakeWharton/status/651220291763331073

Logging in Retrofit v1 is an approximation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment