Skip to content

Instantly share code, notes, and snippets.

@jotathebest
Created February 24, 2019 13:37
Show Gist options
  • Save jotathebest/4fc1c900bd571e037a2dde1a4efc41a8 to your computer and use it in GitHub Desktop.
Save jotathebest/4fc1c900bd571e037a2dde1a4efc41a8 to your computer and use it in GitHub Desktop.
Ubidot HTTP Java Example
/*
* 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 httpexample;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author jose garcia
*/
public class HttpExample {
/**
* @param args the command line arguments
* @throws java.net.MalformedURLException
*/
private static String deviceLabel = "my-device";
private static String variableLabel = "my-variable";
private static String token = "";
private static String endpoint = "https://industrial.api.ubidots.com/api/v1.6/devices";
private static String userAgent = "Java/0.1";
public static void main(String[] args) throws MalformedURLException, IOException {
String ubiEndpoint= endpoint + "/" + deviceLabel;
String testValue = "1";
URL ubiUrl = new URL(ubiEndpoint);
String json = "{\"" + variableLabel + "\":" + testValue + "}";
System.out.println("payload: " + json);
HttpURLConnection con = (HttpURLConnection) ubiUrl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", userAgent);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("X-AUTH-TOKEN", token);
con.setDoOutput(true);
con.setDoInput(true);
try {
con.setRequestMethod("POST");
try (OutputStream os = con.getOutputStream()) {
os.write(json.getBytes("UTF-8"));
}
int responseCode = con.getResponseCode();
System.out.println("response code: " + responseCode);
} catch (ProtocolException ex) {
Logger.getLogger(HttpExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment