问题
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