0

为什么下面的代码只返回一个“{”,即 JSON 字符串的开头而不是整个 JSON?当我在浏览器中输入 URL 时,它会返回完整的 JSON。我试图缓冲响应,但似乎没有任何效果?谁能解释为什么?

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Nasik%20&types=geocode&language=en&sensor=true&key=API-KEY");
HttpResponse response = httpclient.execute(httpget);
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Toast.makeText(this, br.readLine(), Toast.LENGTH_LONG).show();      
4

3 回答 3

1

您正在使用函数 br.readline()。正如函数名所暗示的,它只读取一行。要完全解析它,请使用类似

StringBuilder sb = new StringBuilder();
 String line = null;
 while ((line = br.readLine()) != null) {
    sb.append(line + "\n");
}
Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show();
于 2013-06-14T09:36:47.667 回答
1

试试这个方法。

try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        Log.d("Json Output",sb.toString());
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

更新 :

您需要阅读每一行,目前您正在尝试阅读第一行。

于 2013-06-14T09:36:11.110 回答
1

您只是在阅读回复的第一行。

尝试这样的事情:http ://www.java2s.com/Code/Android/File/ReadInputStreamwithBufferedReader.htm

于 2013-06-14T09:33:18.740 回答