如何从 OkHttp Response 对象中提取原始 JSON 字符串?
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;
}
如果我在调用 getCarros
方法时打印出 json
变量的值,我会在 logcat 中看到以下消息:
com.squareup.okhttp.internal.http.RealResponseBody@1e11866
如何记录我收到的实际 JSON 字符串?
(最初针对 OkHttp 2.5.0 版回答)。
替换
String json = response.body().toString();
和
String json = response.body().string();
response.body
returns 一个 ResponseBody
对象,它有自己的 string
方法:参见来源 here.
kotlin 用户尝试此代码 100% 测试
val result: String = Gson().toJson(response.body()!!.string())
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;
}
如果我在调用 getCarros
方法时打印出 json
变量的值,我会在 logcat 中看到以下消息:
com.squareup.okhttp.internal.http.RealResponseBody@1e11866
如何记录我收到的实际 JSON 字符串?
(最初针对 OkHttp 2.5.0 版回答)。
替换
String json = response.body().toString();
和
String json = response.body().string();
response.body
returns 一个 ResponseBody
对象,它有自己的 string
方法:参见来源 here.
kotlin 用户尝试此代码 100% 测试
val result: String = Gson().toJson(response.body()!!.string())