Created
May 5, 2015 05:22
-
-
Save z0lope0z/9876d27061744e234c42 to your computer and use it in GitHub Desktop.
GZipped Request in OkHttp using Interceptors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Not sure about this but uses a combination of the two: | |
// https://github.com/square/okhttp/issues/350 | |
// https://android.googlesource.com/platform/external/okhttp/+/e78f117bcbd6b57d783737107f445ef75ecb474a/samples/guide/src/main/java/com/squareup/okhttp/recipes/RequestBodyCompression.java | |
public Response proceedGzip(Interceptor.Chain chain) throws IOException { | |
Request originalRequest = chain.request(); | |
Request compressedRequest = originalRequest.newBuilder() | |
.header("Content-Encoding", "gzip") | |
.method(originalRequest.method(), requestBodyWithContentLength(gzip(originalRequest.body()))) | |
.build(); | |
return chain.proceed(compressedRequest); | |
} | |
private RequestBody requestBodyWithContentLength(final RequestBody requestBody) throws IOException { | |
final Buffer buffer = new Buffer(); | |
try { | |
requestBody.writeTo(buffer); | |
} catch (IOException e) { | |
throw new IOException("Unable to copy RequestBody"); | |
} | |
return new RequestBody() { | |
@Override | |
public MediaType contentType() { | |
return requestBody.contentType(); | |
} | |
@Override | |
public long contentLength() { | |
return buffer.size(); | |
} | |
@Override | |
public void writeTo(BufferedSink sink) throws IOException { | |
sink.writeAll(buffer); | |
} | |
}; | |
} | |
private RequestBody gzip(final RequestBody body) { | |
return new RequestBody() { | |
@Override | |
public MediaType contentType() { | |
return body.contentType(); | |
} | |
@Override | |
public long contentLength() { | |
return -1; // We don't know the compressed length in advance! | |
} | |
@Override | |
public void writeTo(BufferedSink sink) throws IOException { | |
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); | |
body.writeTo(gzipSink); | |
gzipSink.close(); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment