Call REST API using JAVA on Raspberry Pi

REST API from Raspberry Pi using JAVA

This video is around Raspberry Pi to showcase the usage of Raspberry Pi in IOT projects and that’s using JAVA. This is going to be a series of video including Sensor interfacing using pi4J, REST API usage with JAVA, MQTT usage with JAVA and finally adding all to the same project and running over Raspberry Pi. In the last video, we saw how to interface DS18B20 1 wire temperature sensor with Raspberry Pi by using JAVA. If you have not checked it out you can do that and for that, I have provided the link down below in the description. This video is the 2nd in the series where we will see how to publish or send sensor data using REST API to cloud. And in this, we are using ThingSpeak as cloud service to publish data. HTTP calls for REST API are done using Unirest lightweight HTTP client library. In the next video, we will do the same by using MQTT.

 

 


Code:

import com.pi4j.component.temperature.TemperatureSensor;
package in.weargenius.restapi;
import java.io.IOException;
import java.io.InputStream;

import com.mashape.unirest.http.*;
import com.mashape.unirest.http.async.Callback;
import com.mashape.unirest.http.exceptions.UnirestException;


public class RESTCall {
	public void sendDataOverRest(int temperature){
		
		Unirest.post("https://api.thingspeak.com/update.json")
		  .header("accept", "application/json")
		  .field("api_key", "0C8704XEZ68UFGB3")
		  .field("field1",temperature)
		  .asJsonAsync(new Callback() {

		    public void failed(UnirestException e) {
		        System.out.println("The request has failed");
		    }

		    public void completed(HttpResponse response) {
		         int code = response.getStatus();
		       //  Map<String, String> headers = response.getHeaders();
		         JsonNode body = response.getBody();
		         InputStream rawBody = response.getRawBody();

			        System.out.println(code);
			        System.out.println(body);
			        System.out.println(rawBody);
			        
			        try {
						Unirest.shutdown();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		    }

		    public void cancelled() {
		        System.out.println("The request has been cancelled");
		    }


		});
	}

}

 

Links :
Github Repo: bit.ly/2sxXweP
Download Unirest Library: bit.ly/2j32blF
Unirest Website: bit.ly/2rFQ2t3
Unirest Jar Download (With Dependencies): bit.ly/2sAbhul
First Part (DS18B20 Interfacing with Raspberry Pi using JAVA): bit.ly/2rxd1WK

Java Application on Pi Playlist: bit.ly/2eB1O2K

Suvendu Swain
Catch Me On

Suvendu Swain

Blogger/ Educationist at WeArGenius
A person passionate about tech stuffs.
Suvendu Swain
Catch Me On

Latest posts by Suvendu Swain (see all)

Related posts