guuilp guuilp - 2 months ago 27
Android Question

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?

Answer

(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.

Comments