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

醉酒当歌 提交于 2019-12-22 09:46:53

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/32598044/how-can-i-extract-the-raw-json-string-from-an-okhttp-response-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!