Search code examples
javagoogle-feed-api

Using Google feed api java


I'm trying to fetch some data using Google feed api. But line = reader.readLine() is always null.

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());

Solution

  • Try this

        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);
    

    Or other way is you can read the content-length header and read that till you get that much data.