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?
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.
JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser. parse(yourString); String msgType = (String) jsonObject. get("MsgType");
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.
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With