首页 > 解决方案 > 如何使用 Retrofit 将参数传递给 POST 请求,然后序列化请求?

问题描述

我正在从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()
            }
        }
    }
}

标签: androidkotlinpostserializationretrofit

解决方案


您应该使用@Body注释

当您想直接控制 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
)

推荐阅读