Guilherme Lima Pereira
Guilherme Lima Pereira

Reputation: 1434

How can I extract the raw JSON string from an OkHttp Response object?

private static final String URL = "http://www.livroandroid.com.br/livro/carros/carros_{tipo}.json";

public static List<Carro> getCarros(Context context, String tipo) throws IOException {
    String url = URL.replace("{tipo}", tipo);
    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder()
            .url(URL)
            .build();
    Response response = okHttpClient.newCall(request).execute();
    String json = response.body().toString();
    List<Carro> carros = parserJSON(context, json);
    return carros;
}

If I print out the value of the json variable when calling the getCarros method, I see the following message in my logcat:

com.squareup.okhttp.internal.http.RealResponseBody@1e11866

How can I log the actual JSON string I received instead?

Upvotes: 14

Views: 22152

Answers (2)

sarjeet singh
sarjeet singh

Reputation: 551

kotlin user try this code 100% tested

val result: String = Gson().toJson(response.body()!!.string())

Upvotes: 1

stkent
stkent

Reputation: 20128

(Originally answered for OkHttp version 2.5.0).

Replace

String json = response.body().toString();

with

String json = response.body().string();

response.body returns a ResponseBody object, which has its own string method: see the source here.

Upvotes: 47

Related Questions