簡體   English   中英

如何在Kotlin中用Retrofit發出正確的POST請求?

[英]How to make a correct POST request with Retrofit in Kotlin?

我想發布這個 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

//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
    }
})

暫無
暫無

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

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