Retrofit 2 — How to Send Plain Text Request Body

Within a previous guide, you’ve learned how to send objects in request body using Retrofit and based on that topic, Marty asked a good question: how to send plain text as payload with a request? That’s exactly what you’ll take away from this guide :)

Before heading towards the details, have a look at all the other posts within this Retrofit series.

Retrofit Series Overview

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

Overview

There are situations where you just need to send plain text as the request payload. Actually, there are multiple solutions to achieve the desired result and we’ll show you two of them. The described solutions apply for any Java primitive, not just string values.

Related to the actual question of how to send plain text within the request body, we’ll await a plain text in response. Retrofit and its converters got your back in both situations.

Solution 1: Scalars Converter

There are multiple existing Retrofit converters for various data formats. You can serialize and deserialize Java objects to JSON or XML or any other data format and vice versa. Within the available converters, you’ll also find a Retrofit Scalars Converter that does the job of parsing any Java primitive to be put within the request body. Conversion applies to both directions: requests and responses.

The scalars converter can be used to serialize your value for the text/plain request payload.

Add Scalars Converter to Your Project

The scalars converter isn’t integrated by default, you need to add the dependency in your build.gradle file. Synchronize your project after adding the new converter-scalars dependency:

compile  'com.squareup.retrofit2:converter-scalars:2.1.0'  

Just the import of the new dependency isn’t sufficient to parse Java primitives appropriately. A second step is required: add the scalars converter to your Retrofit instance. Please be aware that the order you’re adding response converters matters! As a rule of thumb, add Gson as the last converter to your Retrofit instance, because it says “Give it to me baby!” for every type ;-)

Retrofit retrofit = new Retrofit.Builder()  
        .addConverterFactory(ScalarsConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl("https://your.base.url/")
        .build();

Now that you’ve the respective converter for scalars integrated, it’s time for the actual request.

Use Primitives and Boxed Types for Requests & Response

The service interface shown in the snippet below is just an illustration to send and receive text values. Just using Gson for a defined String payload won’t map the data correctly and an error occurs during runtime.

public interface ScalarService {  
    @POST("path")
    Call<String> getStringScalar(@Body String body);
}

Actually, that’s all the magic. Using the scalars converter will add the defined string value accordingly to your request body. Retrofit iterates through the list of available response converters and picks the first that is applicable: the scalars converter.

String body = "plain text request body";  
Call<String> call = service.getStringScalar(body);

Response<String> response = call.execute();  
String value = response.body();  

Requests with primitives are handled exactly the same as with more complex objects. Use the call instance as you would do with any other Java object.

If you don’t want to integrate another converter for the handling of Java primitives, Retrofit (especially OkHttp) got you covered and allows you to leverage the RequestBody class. We’ll show you how to apply that class within the following section.

Solution 2: Use RequestBody Class

Whatever reason holds you back from adding the scalars converter, you don’t depend on it for adding plain text as request payload. You can also use OkHttp’s RequestBody class and create the request body by defining the content type yourself.

The following service interface illustrates the usage of the RequestBody class for payload and we’ll leverage another OkHttp class ResponseBody to accept a primitive value in return.

public interface ScalarService {  
    @POST("path")
    Call<ResponseBody> getStringRequestBody(@Body RequestBody body);
}

The ResponseBody class allows us to receive any response data. The following code snippet shows the usage of both used classes in more detail:

String text = "plain text request body";  
RequestBody body =  
        RequestBody.create(MediaType.parse("text/plain"), text);

Call<ResponseBody> call = service.getStringRequestBody(body);  
Response<ResponseBody> response = call.execute();  
String value = response.body().string();  

As already mentioned, you need to create your request payload yourself by defining the content type for the given data. Use the static RequestBody.create() to create the payload. Finally, the response instance includes the data received from the server. You can access the response body as you would do with any other response type. Using the .string() method allows us to receive the data in string format from the response body.

Using the RequestBody and ResponseBody classes is a bit more complex on your side, because you need to handle the request body creation yourself. The described scalars converter hides this complexity and you can just go ahead and define any Java primitive as the type of request and response body.

Outlook

Within this article, you’ve learned how to create plain text requests using Java primitives like string, int, float, boolean, etc. You can either use the provided Retrofit scalars converter to handle these types or benefit from OkHttp’s classes to manage the request body creation and response conversion for primitives yourself.

Additional Resources


Explore the Library

Find interesting tutorials and solutions for your problems.

Miscellaneous