import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
import kotlin.concurrent.thread
class InterceptorDemoActivity : AppCompatActivity() {
private lateinit var responseTextView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_interceptor_demo)
val makeRequestButton = findViewById<Button>(R.id.makeRequestButton)
responseTextView = findViewById(R.id.responseTextView)
// Create OkHttpClient with interceptor
val client = OkHttpClient.Builder()
.addInterceptor(object : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
// Log request URL
println("Request URL: ${request.url}")
val response = chain.proceed(request)
// Log response code
println("Response code: ${response.code}")
return response
}
})
.build()
makeRequestButton.setOnClickListener {
thread {
try {
val request = Request.Builder()
.url("https://jsonplaceholder.typicode.com/todos/1")
.build()
val response = client.newCall(request).execute()
val body = response.body?.string() ?: "No response body"
runOnUiThread {
responseTextView.text = body
}
} catch (e: IOException) {
runOnUiThread {
responseTextView.text = "Request failed: ${e.message}"
}
}
}
}
}
}We create an OkHttpClient and add an interceptor that prints the request URL and response code to the console. When the user taps the 'Make Request' button, we run a network call on a background thread to avoid blocking the UI. The GET request fetches JSON data from the example API. After getting the response, we update the TextView on the main thread to show the response body. If the request fails, we show an error message instead.