Retrofit — Send Objects in Request Body

This post describes how to define and send data within HTTP request body with Retrofit. Additionally, we have inspirational posts from our Retrofit series for you:

Retrofit Series Overview

  1. Callbacks (Coming soon)
  2. Annotations (Coming soon)
  3. Fluent Interface with Builders (Coming soon)

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 1.9

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

Retrofit 2

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

The defined RestAdapter’s 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 concrete 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 1.9

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

Retrofit 2

Task task = new Task(1, "my task title");  
Call<Task> call = taskService.createTask(task);  
call.enqueue(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"
}

Enjoy! Please get in touch on Twitter @futurestud_io if you run into problems or want more details.


Explore the Library

Find interesting tutorials and solutions for your problems.

Miscellaneous