guuilp guuilp - 6 months ago 56
Android Question

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

private static final String URL = "{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()
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
variable when calling the
method, I see the following message in my logcat:


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


(Originally answered for OkHttp version 2.5.0).


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


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

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