Skip to content

Instantly share code, notes, and snippets.

@hardikm9850
Created March 26, 2025 12:04
Show Gist options
  • Select an option

  • Save hardikm9850/da4ac3e3fb8846a6c6dda980e932b1fb to your computer and use it in GitHub Desktop.

Select an option

Save hardikm9850/da4ac3e3fb8846a6c6dda980e932b1fb to your computer and use it in GitHub Desktop.
// The following code is referenced from the sources below. I encourage you to review + debug it yourself to get a better understanding.
// https://github.com/square/okhttp/issues/350#issuecomment-123105641
// https://github.com/square/okhttp/blob/f4ff4f4a8dce5f44596115f9564280e41d845f98/samples/guide/src/main/java/okhttp3/recipes/RequestBodyCompression.java#L73
private class GzipRequestInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val body = originalRequest.body
if (body == null || originalRequest.header("Content-Encoding") != null
) {
return chain.proceed(originalRequest)
}
val compressedRequest = originalRequest.newBuilder()
.header("Content-Encoding", "gzip")
.method(originalRequest.method, gzip(body))
.build()
return chain.proceed(compressedRequest)
}
private fun gzip(body: RequestBody): RequestBody {
return object : RequestBody() {
override fun contentType(): MediaType? {
return body.contentType()
}
override fun contentLength(): Long {
return -1 // We don't know the compressed length in advance!
}
override fun writeTo(sink: BufferedSink) {
val gzipSink = GzipSink(sink).buffer()
body.writeTo(gzipSink)
gzipSink.close()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment