Retrofit — Send Objects in Request Body

In this tutorial you'll learn how to define and send data within HTTP request body with Retrofit. Sending data to the server is one of the most fundamental tasks of Retrofit. Luckily, it's super easy.

Don't forget, we have more tutorials from our Retrofit series for you:

Retrofit Series Overview

Send Objects as Request Body

Retrofit offers the ability to pass objects within the request body. Objects can be specified for use as HTTP request body by using the @Body annotation. The functionality of Retrofit’s @Body annotation hasn’t changed in version 2.

Retrofit 2

public interface TaskService {  
    @POST("/tasks")
    Call<Task> createTask(@Body Task task);
}

Retrofit 1.9

public interface TaskService {  
    @POST("/tasks")
    void createTask(@Body Task task, Callback<Task> cb);
}

The defined Retrofit converter (like Gson) will map the defined object to JSON and it will finally sent as the request’s body to your defined server.

Example

Let’s look at a specific example.

public class Task {  
    private long id;
    private String text;

    public Task(long id, String text) {
        this.id = id;
        this.text = text;
    }
}

Instantiating a new Task object fills its properties with values for id and text. Further, when passing the object to the service class, the object fields and values will be converted to JSON.

Retrofit 2

Task task = new Task(1, "my task title");  
Call<Task> call = taskService.createTask(task);  
call.enqueue(new Callback<Task>() {});  

Retrofit 1.9

Task task = new Task(1, "my task title");  
taskService.createTask(task, new Callback<Task>)() {});  

Calling the service method createTask will convert the properties of task into JSON representation. The JSON of task will look like this:

{
    "id": 1,
    "text": "my task title"
}

Summary

In this tutorial you've seen how simple it is in Retrofit to send Java objects to the server. Of course, in Retrofit 2, you'll also need to configure the converters correctly. We recommend to read the introduction to converters next.

Please get in touch on Twitter @futurestud_io or in the comments below if you run into problems or want more details.

Enjoy coding & make it rock!


Explore the Library

Find interesting tutorials and solutions for your problems.