Skip to content

Instantly share code, notes, and snippets.

@jgilfelt
Created February 22, 2017 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgilfelt/223978009329d8158d86ee4ea82a3514 to your computer and use it in GitHub Desktop.
Save jgilfelt/223978009329d8158d86ee4ea82a3514 to your computer and use it in GitHub Desktop.
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
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 {
@Rule
public final MockWebServer server = new MockWebServer();
@Test
public void test() throws Exception {
server.enqueue(new MockResponse()
.addHeader("Content-Encoding", "gzip")
.setBody(gzip("abc")));
Request request = new Request.Builder()
.url(server.url("/"))
.build();
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(new BreakingGzipInterceptor())
.build();
Call call = client.newCall(request);
Response response = call.execute();
assertEquals("abc", response.body().string());
}
private static class BreakingGzipInterceptor implements Interceptor {
@Override
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();
System.out.println(body);
}
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