Retrofit2+Kotlin how to see a raw json while get response as data class

Viewed 769

There is a service file:

interface DevbyteService {
    @GET("devbytes.json")
    fun getPlaylist(): Deferred<NetworkVideoContainer>
}

private val moshi = Moshi.Builder()
        .add(KotlinJsonAdapterFactory())
        .build()

object Network {
    // Configure retrofit to parse JSON and use coroutines
    private val retrofit = Retrofit.Builder()
            .baseUrl("https://devbytes.udacity.com/")
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .build()

    val devbytes = retrofit.create(DevbyteService::class.java)
}

So, I get a list of NetworkVideoContainer. This works fine but I want to see also a raw json answer, for example in logs. How to do it?

2 Answers

With Retrofit you should use HttpLoggingInterceptor

Add the dependency in your build.gradle file as below

implementation("com.squareup.okhttp3:logging-interceptor:4.4.0")

And then set a HttpLoggingInterceptor to the Retrofit object as below

private val retrofit = Retrofit.Builder()
                .baseUrl("https://devbytes.udacity.com/")
                .addConverterFactory(MoshiConverterFactory.create(moshi))
                .addCallAdapterFactory(CoroutineCallAdapterFactory())
                .client(okHttpClient)
                .build()

 private val okHttpClient = OkHttpClient.Builder().addInterceptor(
            HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY
            }
    ).build()

In case of deprecation warnings, simply change setLevel to:

  level = HttpLoggingInterceptor.Level.BODY

The above solution gives you logcat messages very similar to the old ones set by

  level = RestAdapter.LogLevel.FULL

In Retrofit 2 you should use HttpLoggingInterceptor.

Add dependency to build.gradle :

implementation 'com.squareup.okhttp3:logging-interceptor:4.4.0'

Create a Retrofit object:

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("YOUR_URL")
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

retrofit.create(ApiClient.class);
Related