Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Gzip with Okhttp to request compression #25

Open
tonilopezmr opened this issue Aug 16, 2018 · 1 comment
Open

Use Gzip with Okhttp to request compression #25

tonilopezmr opened this issue Aug 16, 2018 · 1 comment

Comments

@tonilopezmr
Copy link
Owner

tonilopezmr commented Aug 16, 2018

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
Copy link

I need this too

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants