Java example

This tutorial shows you how to get started using Frost in Java.

First and most importantly, the client ID must be defined to be able to authenticate the requests.

package frost;
//Library needed
import org.apache.commons.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

public class Frost {
    public static void main(String[] args) {
        // Insert your own client ID
        String client_id = args[0];

In the next block of code, we build the URL and perform the request to Frost. Here we use the observations endpoint to get measured data. The three parameters sources, elements and referencetime are defined in this block as they are mandatory for the observations endpoint.

        // Build the URL and define parameters
        String url = "";
        url += "sources=" + "SN18700,SN90450";
        url += "&elements=" + "mean(air_temperature P1D),sum(precipitation_amount P1D),mean(wind_speed P1D)";
        url += "&referencetime=" + "010-04-01/2010-04-03";
        // Replace spaces
        url = url.replaceAll(" ", "%20");
        // Issue an HTTP GET request
        URL Url = new URL(url);
        HttpsURLConnection conn = (HttpsURLConnection) Url.openConnection();      
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64((client_id+":").getBytes("UTF-8"))));
        // Extract JSON data
        JSONObject object = new JSONObject(new JSONTokener(new InputStreamReader(conn.getInputStream())));
        JSONArray data = object.getJSONArray("data");
        JSONArray observations;

Finally, we loop through the JSON structure of the data and echo the time, weather element name and value.

      // Loop through the data
        for (int i = 0; i < data.length(); i++) {
           System.out.println("\n"+object.getString("sourceId") +"  "+object.getString("referenceTime"));
            observations = object.getJSONArray("observations");
                   for (int j= 0; j < observations.length(); j++) {
                       System.out.println(" "+object.getString("elementId") +"="+object.getInt("value")+ "  ("+object.getString("timeOffset")+")");
       }catch(Exception ex){
          System.out.println("Error: the data retrieval was not successful!");