📅  最后修改于: 2023-12-03 15:01:20.328000             🧑  作者: Mango
HttpLoggingInterceptor is a useful tool for logging HTTP requests and responses. With this interceptor, you can easily see what data is being sent and received between your client and the server.
In Kotlin, you can easily add HttpLoggingInterceptor to your OkHttpClient by adding the following code:
val client = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build()
This creates a new OkHttpClient instance with an interceptor that logs both request and response bodies. You can customize the level of logging by changing the Level
parameter to NONE
, BASIC
, HEADERS
, or BODY
. For example, if you only want to see the headers in the logs, you can set the level to HEADERS
.
val client = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
.build()
You can also customize the logging format by creating a Logger
instance and passing it to the interceptor.
val logger = object : HttpLoggingInterceptor.Logger {
override fun log(message: String) {
Log.d("HTTP", message)
}
}
val client = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor(logger).setLevel(HttpLoggingInterceptor.Level.BODY))
.build()
This creates a new logger that logs messages to the Android logcat with a tag of "HTTP". You can also write messages to a file or send them to a remote server instead of logging them to the console.
In conclusion, HttpLoggingInterceptor is a useful tool for debugging HTTP requests and responses in Kotlin. By adding this interceptor to your OkHttpClient, you can easily see what data is being sent and received between your client and the server.