Creating a Hobson Hub HTTP Plugin

Note: This page only applies to Hobson 0.10.0 and higher.

Introduction

Smart devices that are accessible via HTTP/HTTPS are extremely common and therefore Hobson has capabilities to make integration with them very easy. The runtime will automatically handle asynchronous request/response management, response header parsing, response cookie parsing and more.

That isn't to say you can't use your own HTTP client code within your plugin implementation, but why re-invent the wheel?

AbstractHttpClientPlugin

The AbstractHttpClientPlugin class provides all the capabilities needed to interact with hardware via HTTP. The full details are in the SDK Javadoc, but here are the highlights.

Making a request

To make an HTTP request, you call the method:

void sendHttpRequest(URI uri, HttpRequest.Method method, Map<String,String> headers, Collection<Cookie> cookies, byte[] body, Object context)

Note that this method returns void so you will not receive the result of the request as part of this call. There are also several variants of this method that take fewer parameters so null doesn't have to be passed explicitly.

Receiving a response

The AbstractHttpClientPlugin class forces you to implement two methods:

void onHttpResponse(HttpResponse response, Object context)
void onHttpRequestFailure(Throwable cause, Object context)

These callback methods are how you receive the results of a call to the sendHttpRequest method.

As with all Hobson plugin callbacks, the fact that these method names are prefixed with on means that they will always be invoked via the plugin event loop and you don't have to worry about thread synchronization.

Each of these methods includes a context argument. This is necessary since HTTP handling is asynchronous and a correlation mechanism is needed between a single request and its response. The context object in the callback will be identical to the one passed into the sendHttpRequest method for which the response is associated.

onHttpResponse

In the case where a request was successful, the onHttpResponse method is called with an HttpResponse object. This object will contain, among other things, the response body, headers and any cookies the server provided.

onHttpRequestFailure

In the case where there was a failure of some sort, the onHttpRequestFailure method is called with the Throwable cause of the failure.