Your GreenLightning app can also function as a HTTP client for sending REST requests, etc... to other servers and parsing the response.
Please refer to the GreenLightning-API repo for more examples like this one.
Use the code below to get started with creating a HTTP client.
Example
This is an example GreenLightning App in which we want to hit up a server somewhere containing JSON weather data (or see Simple REST Server on how to build your own REST service).
In this example, we build a simple app that performs a GET request to a local server which servers a static JSON file containing "wather data":
First, we create our client. We specify that we are also acting as a HTTP client on line 8, and create the client instance on line 11. We also declare the JSON fields we care about.
Client.java
publicclassClientimplementsGreenApp{privateClientHostPortInstance weatherSession; @OverridepublicvoiddeclareConfiguration(Builder config) {// In this example, we have TLS enabled.HTTPClientConfig netClientConfig =config.useNetClient();// We directly parse JSON of the current session. weatherSession =netClientConfig.createHTTP1xClient("127.0.0.1",443).parseJSON().stringField("condition",WeatherFields.WEATHER_CONDITIONS).decimalField("temperature",WeatherFields.TEMP_KELVIN).finish(); } @OverridepublicvoiddeclareBehavior(GreenRuntime runtime) {// Add the weather behavior here.runtime.addResponseListener(newWeatherBehavior(runtime, weatherSession)).acceptHostResponses(weatherSession); }}
WeatherBehavior will be responsible for sending out the request and receiving the response. We use a HTTPRequestService to do this.
WeatherBehavior.java
publicclassWeatherBehaviorimplementsHTTPResponseListener,StartupListener,ShutdownListener {// Keep track of active session for get request.privateClientHostPortInstance session;// This will actually perform the request.privatefinalHTTPRequestService clientService;publicWeatherBehavior(GreenRuntime runtime,ClientHostPortInstance session) {// Create the request service. clientService =runtime.newCommandChannel().newHTTPClientService();this.session= session; } @Overridepublicvoidstartup() {// Send out the request on startup.clientService.httpGet(session,"/api/weather"); } @OverridepublicbooleanacceptShutdown() {// Close the session when shutting down.returnclientService.httpClose(session); } @OverridepublicbooleanresponseHTTP(HTTPResponseReader reader) {// We need to open the payload data.reader.openPayloadData( (r)-> {// Since we want to directly parse the fields, it needs to be structured.StructuredReader s =r.structured();// Read the fields from JSON.double tempKelvin =s.readDecimalAsDouble(WeatherFields.TEMP_KELVIN);String conditions =s.readText(WeatherFields.WEATHER_CONDITIONS);// Do whatever you'd like with the data here, this is just a short example.// Usually, you would use a PubSub service to send this information back to// another behavior.System.out.println(conditions +", "+ tempKelvin); });returntrue; }}