Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
import org.junit.Rule;
import org.junit.Test;
import okhttp3.Call;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okio.Buffer;
import okio.GzipSink;
import okio.GzipSource;
import okio.Okio;
import static org.junit.Assert.assertEquals;
public class BreakingGzipInterceptorTest {
public final MockWebServer server = new MockWebServer();
public void test() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Content-Encoding", "gzip")
Request request = new Request.Builder()
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(new BreakingGzipInterceptor())
Call call = client.newCall(request);
Response response = call.execute();
assertEquals("abc", response.body().string());
private static class BreakingGzipInterceptor implements Interceptor {
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
String contentEncoding = response.header("Content-Encoding");
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
// decompress and read the gzip encoded body, seems innocent enough...
GzipSource source = new GzipSource(response.body().source());
String body = Okio.buffer(source).readUtf8();
return response;
private static Buffer gzip(String body) throws IOException {
Buffer buffer = new Buffer();
Okio.buffer(new GzipSink(buffer)).writeUtf8(body).close();
return buffer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.