HTTP Client

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
public class Client implements GreenApp
{
    private ClientHostPortInstance weatherSession;

    @Override
    public void declareConfiguration(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();
    }

    @Override
    public void declareBehavior(GreenRuntime runtime) {
        // Add the weather behavior here.
        runtime.addResponseListener(new WeatherBehavior(runtime, weatherSession))
                .acceptHostResponses(weatherSession);
    }
    
}

Create the field identifiers:

WeatherBehavior will be responsible for sending out the request and receiving the response. We use a HTTPRequestService to do this.

Methods

HTTPRequestService.httpGet(ClientHostPortInstance session, String route, optional: HeaderWritable headers)

Sends a GET request to the route (host is defined in session). Optional headers can be written.

You can also write multiple headers:

HTTPRequestService.httpPost(ClientHostPortInstance session, String route, Writable payload)

Sends a POST request to the route (host is defined in session). Optional headers can be written.

HTTPRequestService.httpPost(ClientHostPortInstance session, String route, HeaderWritable headers, Writable payload)

Sends a POST request to the route (host is defined in session) with custom headers.

HTTPRequestService.httpClose(ClientHostPortInstance session)

Closes the current session. Usually, you want to call this in the acceptShutdown() method using a ShutdownListener in your behavior.

Last updated