Skip to content

Instantly share code, notes, and snippets.

@LDuncAndroid
Last active August 1, 2022 00:44
Show Gist options
  • Save LDuncAndroid/0b4eb2f3fc62792621b6310e68fe861d to your computer and use it in GitHub Desktop.
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.
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
}
}
@LDuncAndroid
Copy link
Author

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