Retrofit-Kotlin-Coroutines-Example icon indicating copy to clipboard operation
Retrofit-Kotlin-Coroutines-Example copied to clipboard

Missing Generic Response Code

Open L1f12bscs2109 opened this issue 5 years ago • 1 comments

How can we check status code of response? The code is very beautifully written but i need to know how to get the response code because in interface you are returning List<Users> not Response<Users> so if you want to check mainRespository.getUsers().code you can not do it. I need to check the response code whether it is HTTP_200 , HTTP_UNAUTHORIZED so on. Help will be appreciated, thanks in advance :)

L1f12bscs2109 avatar Jul 10 '20 06:07 L1f12bscs2109

It can be easily doable with the help of HttpLoggingInterceptor. Here is a quick workaround for the RetrofitBuilder.kt:

object RetrofitBuilder {
   
   // Prepare the interceptor
    var intercepter = HttpLoggingInterceptor().apply {
        this.level = HttpLoggingInterceptor.Level.BODY
    }

   // Prepare the client
    private val client = OkHttpClient.Builder().apply {
        this.addInterceptor(intercepter)
    }.build()

    private fun getRetrofit(): Retrofit {
        return Retrofit.Builder()
            .baseUrl(Config.BASE_URL)
            .client(client) // <-- Hook the client right here
            .addConverterFactory(GsonConverterFactory.create())
            .build() //Doesn't require the adapter
    }

    val apiService: ApiService = getRetrofit().create(ApiService::class.java)
}

Filter the Logcat to see logs of OkhttpClient.

rahuldotdev avatar Sep 30 '20 04:09 rahuldotdev