Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

>Solution :

//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
    }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading