Quantcast
Channel: okhttp 3: how to decompress gzip/deflate response manually using Java/Android - Stack Overflow
Viewing all articles
Browse latest Browse all 5

Answer by shengbin_xu for okhttp 3: how to decompress gzip/deflate response manually using Java/Android

$
0
0

Thank you for Aksenov Vladimir`s reply. Your answer saved me a lot of time. Everything is working fine after I upgraded okhttp from 3.x to 4.11.

Here are some additional details:

  1. When users explicitly include the "Accept-Encoding: gzip" header, they need to handle the decompression of the response content themselves.
  2. When users do not explicitly specify "Accept-Encoding" and "Range" okhttp will automatically add "Accept-Encoding: gzip" to the request header, and automatically decompress the response content (if "Content-Encoding" is gzip).

The relevant code is as follows:okhttp3.internal.http.BridgeInterceptor

// If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing    // the transfer stream.    var transparentGzip = false    if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) {      transparentGzip = true      requestBuilder.header("Accept-Encoding", "gzip")    }if (transparentGzip &&"gzip".equals(networkResponse.header("Content-Encoding"), ignoreCase = true) &&        networkResponse.promisesBody()) {      val responseBody = networkResponse.body      if (responseBody != null) {        val gzipSource = GzipSource(responseBody.source())        val strippedHeaders = networkResponse.headers.newBuilder()            .removeAll("Content-Encoding")            .removeAll("Content-Length")            .build()        responseBuilder.headers(strippedHeaders)        val contentType = networkResponse.header("Content-Type")        responseBuilder.body(RealResponseBody(contentType, -1L, gzipSource.buffer()))      }    }

Viewing all articles
Browse latest Browse all 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>