How to poll a URL using the same InputStreamReader

I have an URL that is being constantly updated with new data that i want to retrieve. I wrote this code to retrieve the content every 5 seconds, but the reader is null after one iteration.

InputStream is = new URL("someURL").openStream();
Reader reader = new InputStreamReader(is);
Gson gson = new GsonBuilder().create();
while (true){
    Info info = gson.fromJson(reader, Info.class);
    for (Update update : info.updates){
        if (update.type.equals("data")){
            System.out.println(update.toString());
        }
    }
    Thread.sleep(500);
}

Is it possible to somehow reset the reader and make it read updated data from the stream in the next iteration or do i have to create a new instance of InputStreamReader in each iteration?

Answer

You need to re-create the input stream (i.e. ‘is’). So you need to reopen the connection, again and again. And close it, if you like it to do it while(true).

I don’t believe the reader is null, probable just reached EOS.

Leave a Reply

Your email address will not be published. Required fields are marked *