tonilopezmr / tonilopezmr.github.io

My web portfolio.
https://tonilopezmr-github-io.vercel.app
Other
4 stars 1 forks source link

Use Gzip with Okhttp to request compression #25

Open tonilopezmr opened 6 years ago

tonilopezmr commented 6 years ago

Create a new Interceptor with the code pasted below and add it as an interceptor in Okhttp library builder.

Code

internal class GzipRequestInterceptor : Interceptor {
  @Throws(IOException::class)
  override fun intercept(chain: Interceptor.Chain): Response {
    val originalRequest = chain.request()
    if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
      return chain.proceed(originalRequest)
    }

    val compressedRequest = originalRequest.newBuilder()
        .header("Content-Encoding", "gzip")
        .method(originalRequest.method(), gzip(originalRequest.body()))
        .build()
    return chain.proceed(compressedRequest)
  }

  private fun gzip(body: RequestBody?): RequestBody =
    object : RequestBody() {
      override fun contentType(): MediaType? {
        return body?.contentType()
      }

      override fun contentLength(): Long {
        return -1 // We don't know the compressed length in advance!
      }

      @Throws(IOException::class)
      override fun writeTo(sink: BufferedSink) {
        val gzipSink = Okio.buffer(GzipSink(sink))
        body?.writeTo(gzipSink)
        gzipSink.close()
      }
    }
}

References

Add GZip request compression Interceptors rewriting-request

xavier-rigau commented 5 years ago

I need this too