Last active
August 1, 2022 00:44
-
-
Save LDuncAndroid/0b4eb2f3fc62792621b6310e68fe861d to your computer and use it in GitHub Desktop.
An OKHttp Interceptor that prints the response of a request to the console.
This file contains hidden or 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
import com.squareup.okhttp.Interceptor | |
import com.squareup.okhttp.MediaType | |
import com.squareup.okhttp.Response | |
import com.squareup.okhttp.ResponseBody | |
import okio.BufferedSource | |
import okio.GzipSource | |
import okio.Okio | |
class ResponseBodyLogger : Interceptor { | |
override fun intercept(chain: Interceptor.Chain): Response { | |
val contentEncoding: String = "content-encoding" | |
val request = chain.request() | |
var response = chain.proceed(request) | |
var content: String? = null | |
val body: ResponseBody? = response.body() | |
if (body != null) { | |
val contentType: MediaType = body.contentType() | |
val contentEncoding = response.header(contentEncoding) | |
if ("gzip" == contentEncoding) { | |
val buffer: BufferedSource = Okio.buffer(GzipSource(body.source())) | |
content = buffer.readUtf8() | |
val wrappedBody: ResponseBody = ResponseBody.create(contentType, content) | |
response = response.newBuilder().removeHeader(contentEncoding).body(wrappedBody).build() | |
} else { | |
content = body.string() | |
val wrappedBody: ResponseBody = ResponseBody.create(contentType, content) | |
response = response.newBuilder().body(wrappedBody).build() | |
} | |
} | |
var protocol = response.protocol().name.replaceFirst("_".toRegex(), "/") | |
protocol = protocol.replace('_', '.') | |
val httpLine = "" + protocol + ' ' + response.code() | |
println("OkHttp: ${String.format("%s\n%s\n\n%s", httpLine, response.headers(), content)}") | |
return response | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based upon https://gist.github.com/erickok/e371a9e0b9e702ed441d?permalink_comment_id=3810471#gistcomment-3810471 @flocsy