如何从OkHttp Response对象中提取原始JSON字符串?

Gui*_*ira 3 android json okhttp

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;
}
Run Code Online (Sandbox Code Playgroud)

如果我json在调用getCarros方法时打印出变量的值,我在logcat中看到以下消息:

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

如何记录我收到的实际JSON字符串?

stk*_*ent 20

(最初回答OkHttp版本2.5.0).

更换

String json = response.body().toString();
Run Code Online (Sandbox Code Playgroud)

String json = response.body().string();
Run Code Online (Sandbox Code Playgroud)

response.body返回一个ResponseBody对象,它有自己的string方法:在这里查看源代码.

  • 也适用于OkHttp 3.0.1 (2认同)