Sending form data

Let’s have a look at a theoretical introduction to Retrofit before we move on to coding.

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

Download the starter project here

Github repository

The reason why you might want to send form data to an endpoint is that some APIs require the data that is being sent to them to be encoded in a way that allows them to receive form data, so basically fields that the user can fill out. It depends on the API that you’re working with what it expects. If form data is expected, Retrofit provides an easy way for us to do that.

The way we do that is with the annotation @FormUrlEncoded. To use this annotation, we need a POST request that can carry the data.

@FormUrlEncoded

@POST(“apiCall”)

fun callFormData(@Field(“first_name”) firstName: String,

                 @Field(“last_name”) lastName: String): Call<ApiCallResponse>

The order of annotations on the function doesn’t matter as long as they are both present. In the function we have the fields that we want to send that are marked with the annotation @Field.

In order to have the project run we need to update the ApiCallService function to call the function we’ve just created.

fun call(context: Context) =

    getApi(context).callFormData(“James”, “Bond”)

form data single

Sending multiple fields

If you have a rather large form, or maybe one that tends to change quite often. The API might be able to handle multiple fields and the form might change according to requirements. In that case it would be quite inconvenient to go into the code and change this methods constantly.

For this reason we might want to use multiple fields that can send as many fields as necessary inside a map. The annotation is @FieldMap and it simply takes a map of elements.

@FormUrlEncoded

@POST(“apiCall”)

fun callFormData(@FieldMap fields: Map<String, String>): Call<ApiCallResponse>

Updating the ApiCallService class we get

fun call(context: Context) =

        getApi(context).callFormData(hashMapOf(Pair(“name”, “Alex”), Pair(“lastname”, “Smith”)))

form data multiple

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

Close Bitnami banner
Bitnami