<-- Go Back

Since I first created this post Retrofit and OkHttp have changed a lot. Now in version 2 is much easier to get a String response from your server. All this methods can be seen on Retrofit CallTest class, but I'll write them down anyway.

Method 1

Get the String straight from the response body. Clean and easy:

interface Service {
    @GET("/") Call getBody();
}

// Nothing to add in your builder
Retrofit retrofit = new Retrofit.Builder()  
        .baseUrl(server.url("/"))
        .build();
Service example = retrofit.create(Service.class);

// get your response, sync or async
Response response = example.getBody().execute();
// get the damn string!
response.body().string()

Method 2

Use the new ConverterFactories. This has more code, though to me it is better architecture wise. Copy ToStringConverterFactory to your app. You can find it here.

interface Service {
    @GET("/") Call getString();
}

// Use it in your Retrofit  builder
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(server.url("/"))
        .addConverterFactory(new ToStringConverterFactory())
        .build();
Service example = retrofit.create(Service.class);

// get your response, sync or async, already as a String
Response response = example.getString().execute();
// get the body
response.body()

Original post (Retrofit 1.9):

Not all APIs always respond with JSON. Sometimes you just want a simple response with a text. And when using Retrofit this can be tough. Retrofit always uses GSON (or another converter you decide) to parse the Response. So, if you try to get a Response as String, your code will throw some exceptions regarding tokens and blablabla. One way to not parse the response is to get the Response object.

The problem is that the Response#getBody doesn't return a String, but a TypedInput. And if you try to use toString, the method will not really return the response. So, how you can get only the response, as a String?

Looking at the Retrofit code you can see that TypedInput is an Interface and you can cast it to TypedByteArray so you can see the byte[] inside the response. With this, you can create a new String from the bytes and have your String response, yey!

new String(((TypedByteArray) response.getBody()).getBytes());

Share: twitter facebook
Created: 2015-02-13
blog comments powered by Disqus