Retrofit – Send Objects in Request Body

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, I have previous tutorials in this Retrofit series, make sure you look at it first:

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

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.

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

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

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.

Remember to get in touch in the comments section below if you run into problems or want more details.

Happy Coding!

More From Android Study:

Comments are closed.