Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.vmanolache.mqttpolling; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import java.net.HttpURLConnection; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.json.JSONException; import org.json.JSONObject; /** * * @author vmanolache */ public class Polling { final int SECONDS = 20 * 60; private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); /** * @param args the command line arguments */ public static void main(String[] args) { Polling polling = new Polling(); polling.startPolling(); } private void startPolling() { final Runnable beeper = new Runnable() { @Override public void run() { System.out.println("Executing MQQT post"); try { sendPost(); } catch (UnsupportedEncodingException | JSONException ex) { Logger.getLogger(Polling.class.getName()).log(Level.SEVERE, null, ex); } } }; scheduler.scheduleAtFixedRate(beeper, 10, SECONDS, TimeUnit.SECONDS); } private void sendPost() throws UnsupportedEncodingException, JSONException { try { String url = "http://localhost:8080/notifications"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestMethod("POST"); /** * POSTing * */ OutputStream os = connection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery()); // should be fine if my getQuery is encoded right yes? writer.flush(); writer.close(); os.close(); connection.connect(); int status = connection.getResponseCode(); System.out.println(status); } catch (IOException ex) { Logger.getLogger(Polling.class.getName()).log(Level.SEVERE, null, ex); } } private String getQuery() throws UnsupportedEncodingException, JSONException { JSONObject jobj = new JSONObject(); jobj.put("subject", "Good evening"); jobj.put("content", "infidels..."); return jobj.toString(); } }