【问题标题】:Retrofit2 returns a null response body with GETRetrofit2 使用 GET 返回一个空响应正文
【发布时间】:2020-11-12 05:37:17
【问题描述】:

我正在使用 Retrofit2 对 github api 进行 GET,但 response.body() 返回空。我实际上检查了 Postman 上的端点,它返回了一个正文。我不知道我做错了什么导致了这种情况。我已在我的界面、视图模型和布局下方的帖子中包含。

API 接口

const val BASE_URL = "https://api.github.com/"
private val retrofit =
Retrofit.Builder().addConverterFactory(ScalarsConverterFactory.create()).baseUrl(
    BASE_URL
).build()

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

interface GithubApiService {

@GET("search/users?sort=repositories&order=desc")
fun searchUsers(
    @Query("q") query: String,
    @Query("page") page: Int,
    @Query("per_page") itemsPerPage: Int
): Call<String>
}

视图模型

class OverviewViewModel : ViewModel() {

private val _response = MutableLiveData<String>()
val response: LiveData<String>
    get() = _response

init {
    getGithubUsers()
}

private  fun getGithubUsers() {
    GithubUserApi.retrofitService.searchUsers("location:LOCATION", 1, 50).enqueue(
        object : Callback<String> {
            override fun onFailure(call: Call<String>, t: Throwable) {
                _response.value = "Failure: " + t.message
            }

            override fun onResponse(call: Call<String>, response: Response<String>) {
                _response.value = response.body()
            }
        }
    )

}
}

布局

<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<data>
    <variable
        name="overviewViewModel"
        type="com.example.OverviewViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.overview.OverviewFragment">


<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{overviewViewModel.response}"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

【问题讨论】:

    标签: api kotlin github retrofit2


    【解决方案1】:

    允许数据绑定观察带有片段/活动生命周期的 LiveData。

    binding.lifecycleOwner = this
    

    这就是为我解决问题的方法......真是个疏忽!

    【讨论】:

      猜你喜欢
      • 2013-11-28
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 2019-02-24
      • 1970-01-01
      相关资源
      最近更新 更多