Retrofit2+Kotlin 如何在将响应作为数据 class 时查看原始 json

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

有一个服务文件:

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)
}

所以,我得到了 NetworkVideoContainer 的列表。这工作正常,但我还想看到原始 json 答案,例如在日志中。 怎么做?

在 Retrofit 2 中你应该使用 HttpLoggingInterceptor.

添加对 build.gradle 的依赖:

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

创建一个 Retrofit 对象:

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);

对于 Retrofit,您应该使用 HttpLoggingInterceptor

在您的 build.gradle 文件中添加依赖项,如下所示

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

然后为 Retrofit 对象设置一个 HttpLoggingInterceptor,如下所示

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()

如果出现弃用警告,只需将 setLevel 更改为:

  level = HttpLoggingInterceptor.Level.BODY

以上解决方案为您提供了 logcat 与

设置的旧消息非常相似的消息
  level = RestAdapter.LogLevel.FULL