Friday, 26 May 2017

How to listen to JSON file update using java

I create java program that load JSON file from url , I push json object to this url every 20 seconds I want the program to give notification when the JSON file updated here is my java code

package com.company;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;

public class Main {
    private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
        sb.append((char) cp);
    }
    return sb.toString();
}

public static JSONArray readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONArray jsonArray = new JSONArray(jsonText);
        return jsonArray;
    } finally {
        is.close();
    }
}

public static void main(String[] args) throws IOException, JSONException {
    JSONArray json = readJsonFromUrl("http://frozen-brook-16337.herokuapp.com/history.json");
    for(int i=0;i<json.length();i++){
        JSONObject jo=json.getJSONObject(i);
        System.out.println(jo.get("data"));
     }

 }

}



via Kiki Rizki Arpiandi

No comments:

Post a Comment