You need to enable JavaScript to run this app. 使用Retrofit2调用GitHub API发起GET请求时response.body()返回为空
优惠活动
大模型
产品
解决方案
定价
更多

使用Retrofit2调用GitHub API发起GET请求时response.body()返回为空

Retrofit2调用GitHub API返回空响应体的核心原因与修复方案

核心问题定位

  • 未校验接口响应状态:Retrofit中只要响应状态码不在2xx成功范围,response.body()就会直接返回null,此时错误内容存储在response.errorBody()中。原代码未判断response.isSuccessful()就直接读取body,遇到4xx/3xx类错误时必然拿到空值。
  • 请求配置缺失:未携带GitHub API要求的标准请求头,容易触发接口限流返回403错误;同时在@GET注解中硬编码查询参数,后续调整排序规则时维护成本高。
  • 数据绑定缺失生命周期:布局中直接将LiveData绑定给TextView时,未给布局设置对应的LifecycleOwner,LiveData的数据变化无法被UI感知,表现和“response为空”完全一致。

修复后的代码实现

API层重构

const val BASE_URL = "https://api.github.com/"

// 配置OkHttp客户端,补充GitHub API要求的标准请求头
private val okHttpClient = OkHttpClient.Builder()
    .addInterceptor { chain ->
        val request = chain.request().newBuilder()
            .header("Accept", "application/vnd.github+json")
            .build()
        chain.proceed(request)
    }
    .build()

private val retrofit = Retrofit.Builder()
    .addConverterFactory(ScalarsConverterFactory.create())
    .baseUrl(BASE_URL)
    .client(okHttpClient)
    .build()

object GithubUserApi {
    val retrofitService: GithubApiService by lazy {
        retrofit.create(GithubApiService::class.java)
    }
}

interface GithubApiService {
    // 移除硬编码查询参数,统一通过@Query传递,方便后续维护
    @GET("search/users")
    fun searchUsers(
        @Query("q") query: String,
        @Query("sort") sort: String = "repositories",
        @Query("order") order: String = "desc",
        @Query("page") page: Int,
        @Query("per_page") itemsPerPage: Int
    ): Call<String>
}

ViewModel层修正

class OverviewViewModel : ViewModel() {
    private val _response = MutableLiveData<String>()
    val response: LiveData<String>
        get() = _response

    init {
        getGithubUsers()
    }

    private fun getGithubUsers() {
        GithubUserApi.retrofitService.searchUsers(
            query = "location:Beijing",
            page = 1,
            itemsPerPage = 50
        ).enqueue(
            object : Callback<String> {
                override fun onFailure(call: Call<String>, t: Throwable) {
                    _response.value = "请求失败:${t.localizedMessage}"
                }

                override fun onResponse(call: Call<String>, response: Response<String>) {
                    // 先判断响应是否成功,区分正常响应与错误响应
                    if (response.isSuccessful) {
                        _response.value = response.body() ?: "响应解析后为空"
                    } else {
                        // 读取错误响应内容,方便定位限流、路径错误等问题
                        val errorMsg = response.errorBody()?.string() 
                            ?: "未知错误,接口返回状态码${response.code()}"
                        _response.value = "接口返回错误:$errorMsg"
                    }
                }
            }
        )
    }
}

绑定层修复

布局使用DataBinding绑定LiveData时,必须在对应UI组件中关联生命周期,否则LiveData更新无法触发界面刷新。
在绑定布局的Fragment中补充生命周期配置:

class OverviewFragment : Fragment() {
    private var _binding: FragmentOverviewBinding? = null
    private val binding get() = _binding!!

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val viewModel = ViewModelProvider(this)[OverviewViewModel::class.java]
        binding.overviewViewModel = viewModel
        // 给布局绑定生命周期,LiveData才能被正确观察
        binding.lifecycleOwner = viewLifecycleOwner
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.12.05 09:06:03