Retrofit request body

How can we send information through the body of a POST request

For a more complete and in-depth explanation, check out our complete Retrofit course

Download the starter project here

Github repository

In this article we will discuss sending information to the backend server through the request body instead of the query parameters as we’ve done previously.

The way we do that is through a POST request. That is the main idea behind a POST request, it allows us to not have all the parameters in the query, but to hide in a sense the information inside the body of the request. You can of course have query parameters in a POST request as well if needed.

That is done through a @POST annotation to indicate a HTTP POST request, then we use the @Body annotation to pass the information that we want.

@POST(“user/info“)

fun callPost(@Body name: String): Call<ApiCallResponse>

In the body of the request we can also send objects. Since we’re using the JSON converter it gives us a way to transform an object into a String that we can pass to the body. So that means we can also pass Java or Kotlin objects through the body.

@POST(“apiCall”)

fun callPost(@Body user: User): Call<ApiCallResponse>

In order to test this functionality we need to update the ApiCallService class to call the new

fun call() =

    api.callPost(User(“John”, “abc”))

GsonConverterFactory.create()

post request

For a more complete and in-depth explanation, check out our complete Retrofit course

Close Bitnami banner
Bitnami