如何在Kotlin中使用Retrofit进行正确的POST请求?

6kkfgxo0  于 2022-12-04  发布在  Kotlin
关注(0)|答案(1)|浏览(289)

我想发布这个json:

{
          "user": {
            "name": "Mike",
            "age": "26",
          }
       }

但当我用这种方法时

@Headers("Content-Type: application/json")
@POST("users")
suspend fun postUser(@Body user: User)

我把这个json发送到服务器:

{
   "name": "Mike",
   "age": "26",
}

如何在请求的主体中包含密钥user

r3i60tvu

r3i60tvu1#

//1. Create an interface with the appropriate annotations:

interface ApiService {
    @POST("path/to/endpoint")
    fun postRequest(@Body body: Map<String, Any>): Call<ResponseBody>
}

//2. Create an instance of Retrofit:

val retrofit = Retrofit.Builder()
    .baseUrl("base_url")
    .addConverterFactory(GsonConverterFactory.create())
    .build()

//3. Create an instance of the interface:

val apiService = retrofit.create(ApiService::class.java)

//4. Create the request body:

val body = mapOf(
    "key1" to "value1",
    "key2" to "value2"
)

//5. Make the request:

apiService.postRequest(body).enqueue(object : Callback<ResponseBody> {
    override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
        // handle the response
    }

    override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
        // handle the failure
    }
})

相关问题