簡體   English   中英

Retrofit 響應始終為 null

[英]Retrofit response is always null

我正在嘗試從 gitHub Api 但 retrofit 響應始終返回 Z37A6258660C1DAE299A7DFFFFZA7 獲取用戶名。 當我嘗試在 toast 中顯示用戶名時,我看到:null。 我嘗試更改 retrofit 路徑,但沒有成功。 一切看起來都很好,但我不知道為什么我總是收到這個錯誤。

interface GitHubApi{

@GET("/users/{user}")
fun getUser(@Path("user") user: String): Call<User>

companion object Factory {
    fun getClient(): GitHubApi {
        val url = "https://api.github.com/"

        val interceptor = HttpLoggingInterceptor()
            .apply { level = HttpLoggingInterceptor.Level.BODY }

        val okHttpClient = OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .build()

        val retrofit = Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build()

        return retrofit.create(GitHubApi::class.java)
    }
}}

用戶 model:

data class User(val userName: String)

主要活動:

    private fun createApiService() : GitHubApi{
    val url = "https://api.github.com/"

    val interceptor = HttpLoggingInterceptor()
        .apply { level = HttpLoggingInterceptor.Level.BODY }

    val okHttpClient = OkHttpClient.Builder()
        .addInterceptor(interceptor)
        .build()

    val retrofit = Retrofit.Builder()
        .baseUrl(url)
        .addConverterFactory(GsonConverterFactory.create())
        .client(okHttpClient)
        .build()

    return retrofit.create(GitHubApi::class.java)
}

private fun loadData() {
    val api  = GitHubApi.getClient()

    api.getUser("fabpot").enqueue(object : Callback<User> {
        override fun onFailure(call: Call<User>, t: Throwable) {
            t.printStackTrace()
        }

        override fun onResponse(
            call: Call<User>,
            response: Response<User>
        ) {
            if (!response.isSuccessful) {
                runOnUiThread { showErrorMessage(response.code().toString()) }
            }

            response.body()?.let { showErrorMessage(it.repoName) }
        }
    })
}

嘗試在@GET方法中刪除開頭的斜杠“/”。

github api 中不存在密鑰用戶名。

嘗試以這種方式編輯您的數據 class。

data class User(val name: String)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM