You need to enable JavaScript to run this app. 如何在Android中使用Retrofit2获取完整JSON Response并打印到Logcat
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android中使用Retrofit2获取完整JSON Response并打印到Logcat

Android Retrofit2 输出完整JSON响应到Logcat实现方案

以下是三种不同场景下的实现方式,可根据实际需求选择:


方案1:使用OkHttp官方HttpLoggingInterceptor(全局通用,推荐)

Retrofit底层依赖OkHttp,通过官方提供的日志拦截器可以一键实现完整请求、响应内容打印:

  • 第一步:添加依赖,注意版本需和项目内OkHttp版本保持一致
    dependencies {
        implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0'
    }
    
  • 第二步:配置拦截器并绑定到OkHttp客户端
    // Kotlin示例
    val loggingInterceptor = HttpLoggingInterceptor().apply {
        // 必须设置为BODY级别,才能打印完整的请求、响应JSON内容
        level = HttpLoggingInterceptor.Level.BODY
    }
    
    val okHttpClient = OkHttpClient.Builder()
        .addInterceptor(loggingInterceptor)
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build()
    
    // Java示例
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();
    
  • 第三步:将自定义OkHttp客户端绑定到Retrofit
    val retrofit = Retrofit.Builder()
        .baseUrl("你的接口BaseUrl")
        .client(okHttpClient) // 绑定配置了日志拦截器的客户端
        .addConverterFactory(GsonConverterFactory.create())
        .build()
    

注意:仅在测试环境开启该拦截器,生产环境务必关闭,避免泄露敏感数据、产生不必要的性能损耗


方案2:自定义拦截器(适合需要自定义日志格式的场景)

如果需要对日志格式做定制化处理,可以自己实现拦截器读取响应内容:

class FullResponseLogInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        // clone缓冲区读取响应内容,不会影响后续Retrofit对响应体的解析
        val responseJson = response.body?.source()?.let { source ->
            source.request(Long.MAX_VALUE)
            source.buffer.clone().readString(Charsets.UTF_8)
        }
        // 输出到Logcat,标签可自定义
        Log.d("FullResponseJSON", "请求地址:${request.url}\n响应内容:$responseJson")
        return response
    }
}

配置方式和官方拦截器一致,将自定义拦截器添加到OkHttpClient的拦截器列表即可。


方案3:单个接口单独打印(不需要全局配置的场景)

如果只需要给特定接口打印响应内容,可以直接在请求回调中读取原始响应体:

  • 定义API接口时返回类型指定为Response<ResponseBody>
    interface ApiService {
        @GET("目标接口路径")
        suspend fun getTestData(): Response<ResponseBody>
    }
    
  • 在请求回调中读取响应内容
    viewModelScope.launch {
        val response = apiService.getTestData()
        if (response.isSuccessful) {
            // string()方法只能调用一次,需先存到变量中再做后续处理
            val jsonStr = response.body()?.string()
            Log.d("SingleResponseJSON", "接口返回内容:$jsonStr")
            // 后续可自行将jsonStr解析为对应的业务实体类
        }
    }
    

内容的提问来源于stack exchange,提问作者GLS Mscit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 23:42:02