首页 > 解决方案 > 改造:如何将值发送到 REST API 并检查它是否存在?

问题描述

首先,我是第一次在 Kotlin Android 中使用 Retrofit。

所以我想要的逻辑是这样的:

  1. 我想将用户名发送到 Rest API。
  2. 然后检查它是否存在。
  3. 如果它存在,我想制作一条 Toast 消息,如果它不存在False则为true

所以,我在这个 URL 中有这个 JSON: https://jsonplaceholder.typicode.com/users:

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz"
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "Shanna@melissa.tv"
  },
  {
    "id": 3,
    "name": "Clementine Bauch",
    "username": "Samantha",
    "email": "Nathan@yesenia.net"
  }
]

因此,让我通过 Retrofit 浏览我的代码内容

模型类

class FakeUserModel {
    @Expose
    @SerializedName("username")
    val username: String = ""
}

改造 Api 客户端

object FakeUserApiClient {
  var BASE_URL:String="https://jsonplaceholder.typicode.com/"
  val getFakeUserClient: ApiInterface
    get() {

        val gson = GsonBuilder()
            .setLenient()
            .create()
        val interceptor = HttpLoggingInterceptor()
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)

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

        val retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()

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

这个 ApiInterface 向您演示用于向服务器发送数据的功能:

API接口

interface ApiInterface {
     @FormUrlEncoded
     @POST("users")
     fun check( @Field("username") username:String ): Call<FakeUserModel>
}

所以最后,在活动中我想收到告诉我它是否存在的响应......

活动课

checkButton.setOnClickListener {
    val username = userName.text.toString().trim()

    FakeUserApiClient.getFakeUserClient.check(username)
        .enqueue(object : Callback<FakeUserModel>{
            override fun onFailure(call: retrofit2.Call<FakeUserModel>, t: Throwable) {
                Toast.makeText(applicationContext, t.message, Toast.LENGTH_LONG).show()
            }

            override fun onResponse(
                call: retrofit2.Call<FakeUserModel>,
                response: Response<FakeUserModel>
            ) {
                if (response != null) {
                    Toast.makeText(applicationContext, "true", Toast.LENGTH_LONG).show()
                }else{
                    Toast.makeText(applicationContext, "false", Toast.LENGTH_LONG).show()
                }
            }

        })
}

当我执行应用程序时,它总是说true,即使我传递的用户名不在 JSON 上……那么,伙计们,我的代码有问题吗?我错过了什么?有更好的方法吗?谢谢!

标签: androidkotlinretrofit2

解决方案


更改此 ApiInterface

interface ApiInterface {
 @GET("users")
 fun check( @Query("username") username: String ): Call<FakeUserModel>
}

当用户名存在时,您将收到如下网址的响应 - https://jsonplaceholder.typicode.com/users?username=Bret

[
 {
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
  "street": "Kulas Light",
  "suite": "Apt. 556",
  "city": "Gwenborough",
  "zipcode": "92998-3874",
  "geo": {
    "lat": "-37.3159",
    "lng": "81.1496"
  }
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
  "name": "Romaguera-Crona",
  "catchPhrase": "Multi-layered client-server neural-net",
  "bs": "harness real-time e-markets"
}
}  ]

当用户名不存在时,您将得到空响应 Url - https://jsonplaceholder.typicode.com/users?username=Bre

[]

推荐阅读