How to send a String body with Retrofit
Retrofit uses converters like those for GSON or Moshi to convert a data object to the response body (serialize on some way, typically to JSON format). All that a developer needs to do is pass that data object to a Retrofit service, which would perform the serialization internally.
However, sometimes we would want to provide a String body to Retrofit directly, whether it is because we have already serialized the body beforehand, or the API expects some non-standard body format and we need to build the body manually. This post explains how to do it.
First of all, we need to add a Scalars Converter to the list of our Gradle dependencies, which would take care of converting java.lang.String
objects to text/plain
request bodies, as per their readme. Please check this link for the latest version.
dependencies {
implementation “com.squareup.retrofit2:converter-scalars:2.4.0”
..
}
Then, we need to pass a correct converter factory to our Retrofit builder. It will later tell Retrofit how to convert the @Body
parameter passed to the service.
val retrofit = Retrofit.Builder()
.client(okHttpClient)
.baseUrl("/")
.addConverterFactory(ScalarsConverterFactory.create())
.build()
After this, it is time for setting up a Retrofit service with a String body parameter.
@POST("test")
fun submit(@Body body: String): Call<Void>
At this stage, we are almost done. However, the Scalars converter would try to send the body as text/plain
by default since it is expecting us to send the body in plain text. In case when a data object is serialized as a JSON String and the API endpoint expects a JSON body, we need to explicitly tell Retrofit to add an application/json
content type header. Our complete interface method then would look the following way:
@Headers("Content-Type: application/json")
@POST("test")
fun submit(@Body body: String): Call<Void>
This is it! Now you are equipped with a minimalistic example of sending a String body using Retrofit. Thank you for reading this post.