Search code examples
androidapikotlinretrofitresponse

How to call httpLoggingInterceptor inside request.newBuilder()


As I researched and found that , .client(OkHttptvariableName)
is used inside builder inorder to print the api response into logcat.

But in my case, I cannot call the .client inbuild method with request.newBuilder.
Following is my code snippets.
Please help me.

 val httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        val okHttpClient: OkHttpClient = OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build()


when {
            UserInfo.loginStatus -> {
                request = request.newBuilder()
                    .header("Authorization", UserInfo.token)
                    .build()
            }
            else -> {
                request = request.newBuilder()

                    .build()
            }
        }

Solution

  • See this example:

            val httpClient = OkHttpClient.Builder()
    
            if (BuildConfig.DEBUG) {
                val logging = HttpLoggingInterceptor()
                logging.setLevel(HttpLoggingInterceptor.Level.BODY)
                httpClient.addInterceptor(logging)
            }
    
            Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(httpClient.build())
                    .build()
        }
    

    for more info see: https://futurestud.io/tutorials/retrofit-2-enable-logging-for-development-builds-only