【问题标题】:How to pass parameters to POST request using Retrofit and then serialize request?如何使用 Retrofit 将参数传递给 POST 请求,然后序列化请求?
【发布时间】:2021-06-26 12:00:23
【问题描述】:

我正在从 iOS 切换到 Android 并尝试使用 Retrofit 实现 POST 请求,但不明白我的错,请检查我的代码,并会告诉我哪里出错了。

通过 Postman 一切正常,正文原始值:{"players": ["player"], "action" : "add"}

我的代码下面没有数据类。

界面

interface ApiRequests {
    @POST("/startup")
    fun getDataVenom(
        @Field("players") players: Array<String>,
        @Field("action") action: String
    ): Call<ObjectFromResponse>
}

获取数据:

   private fun getCurrentData() {
        tv_textView.visibility = View.GONE
        tv_timeStamp.visibility = View.GONE
        progressBar.visibility = View.VISIBLE

    val api2 = Retrofit.Builder()
        .baseUrl(BASE_URL_VENOM)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
        .create(ApiRequests::class.java)

     val players: Array<String> = arrayOf("players")

    GlobalScope.launch(Dispatchers.IO) {
        try {
            val response = api2.getDataVenom(players = players, action = "add").awaitResponse()
            if (response.isSuccessful) {

                val data = response.body()!!
                Log.d(TAG, data.toString())

                withContext(Dispatchers.Main) {
                    tv_textView.visibility = View.VISIBLE
                    tv_timeStamp.visibility = View.VISIBLE
                    progressBar.visibility = View.GONE
                }

            }
        } catch (e: Exception) {
            withContext(Dispatchers.Main){
                Toast.makeText(
                    applicationContext,
                    "Seems like something went wrong...",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }
}

【问题讨论】:

    标签: android kotlin post serialization retrofit


    【解决方案1】:

    你应该使用@Body annotation:

    当您想直接控制 POST/PUT 请求的请求体时,在服务方法参数上使用此注解...对象将使用 Retrofit 实例 Converter 进行序列化,结果将直接设置为请求体.正文参数不能为空。

    你可能会使用

    @POST("/startup")
    fun getDataVenom(
        @Body body: BodyDTO
    ): Call<ObjectFromResponse>
    

    BodyDTO 在哪里

    data class BodyDTO(
        @SerializedName("players") private val players: Array<String>,
        @SerializedName("action") private val action: String
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 2014-01-30
      • 2020-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多