2015-09-16 36 views
3
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:如何從OkHttp響應對象中提取原始JSON字符串?

[email protected]

如何記錄我收到的實際JSON字符串?

回答

16

(最初爲OkHttp版本2.5.0回答)。

替換

String json = response.body().toString(); 

String json = response.body().string(); 

response.body返回ResponseBody對象,它具有它自己的string方法:參見源here

+2

也適用於OkHttp 3.0.1 – cwhsu

相關問題