Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 340
Guilherme Lima Pereira Avatar asked Sep 16 '15 00:09

Guilherme Lima Pereira


People also ask

How do I get JSON from OkHttp response?

OkHttp Response To implement our JSON decoder, we need to extract the JSON from the result of the service call. For this, we can access the body via the body() method of the Response object.

How extract JSON data from String in Java?

JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser. parse(yourString); String msgType = (String) jsonObject. get("MsgType");

How do you use OkHttp in Kotlin?

To get include the latest version of OkHttp in your app's gradle file. Sync the project to download the library. Once that is done, I developed a Kotlin class file, called OkHttpRequest. This class is used to make requests and to parse response.


1 Answers

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

like image 167
stkent Avatar answered Oct 20 '22 20:10

stkent