Home > Software engineering >  How to make a correct POST request with Retrofit in Kotlin?
How to make a correct POST request with Retrofit in Kotlin?

Time:12-04

I would like to post this json:

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

but when I use this method

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

I send this json to the server:

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

How to include the key user in the body of my request?

CodePudding user response:

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