1

我正在尝试使用 Google feed api 获取一些数据。但是 line = reader.readLine() 始终为空。

URL url = new URL("https://ajax.googleapis.com/ajax/services/feed/find?" +
                    "v=1.0&q=Official%20Google%20Blog");
            URLConnection connection = url.openConnection();
            String line;
            StringBuilder builder = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while((line = reader.readLine()) != null) {
             builder.append(line);
            }

            JSONObject json = new JSONObject(builder.toString());
4

1 回答 1

1

尝试这个

    URL url = new URL("https://ajax.googleapis.com/ajax/services/feed/find?" +
            "v=1.0&q=Official%20Google%20Blog");
    URLConnection connection = url.openConnection();

    ByteArrayOutputStream content = new ByteArrayOutputStream();

    InputStream is = connection.getInputStream();
    int len = 0;
    byte[] buffer = new byte[1024];
    while ((len = is.read(buffer)) >= 0)
    {
        content.write(buffer, 0, len);
    }
    byte[] finalContent = content.toByteArray();
    String str = new String(finalContent, "UTF8");
    System.out.print(str);

或者其他方式是您可以读取content-length标题并读取它,直到您获得那么多数据。

于 2013-06-18T14:22:55.517 回答