Skip to content

Instantly share code, notes, and snippets.

@swankjesse
Created July 1, 2013 14:02
Show Gist options
  • Save swankjesse/5901027 to your computer and use it in GitHub Desktop.
Save swankjesse/5901027 to your computer and use it in GitHub Desktop.
import com.squareup.okhttp.HttpResponseCache;
import com.squareup.okhttp.OkHttpClient;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;
public class OkHttpGzipCachingExample {
public static void main(String[] args) throws IOException {
String tmp = System.getProperty("java.io.tmpdir");
File cacheDir = new File(tmp, "HttpCache-" + UUID.randomUUID());
HttpResponseCache cache = new HttpResponseCache(cacheDir, Integer.MAX_VALUE);
OkHttpClient client = new OkHttpClient()
.setResponseCache(cache);
URL url = new URL("https://api.github.com/repos/square/okhttp/contributors");
HttpURLConnection connection1 = client.open(url);
System.out.println(readAscii(connection1));
System.out.println(" request count = " + cache.getRequestCount());
System.out.println(" network count = " + cache.getNetworkCount());
System.out.println(" hit count = " + cache.getHitCount());
System.out.println("input stream class = " + connection1.getInputStream().getClass());
HttpURLConnection connection2 = client.open(url);
System.out.println(readAscii(connection2));
System.out.println(" request count = " + cache.getRequestCount());
System.out.println(" network count = " + cache.getNetworkCount());
System.out.println(" hit count = " + cache.getHitCount());
System.out.println("input stream class = " + connection2.getInputStream().getClass());
}
private static String readAscii(URLConnection connection, int count) throws IOException {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
InputStream in = httpConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST
? connection.getInputStream() : httpConnection.getErrorStream();
StringBuilder result = new StringBuilder();
for (int i = 0; i < count; i++) {
int value = in.read();
if (value == -1) {
in.close();
break;
}
result.append((char) value);
}
return result.toString();
}
private static String readAscii(URLConnection connection) throws IOException {
return readAscii(connection, Integer.MAX_VALUE);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment