09.04.2018 Views

tornadofx-guide

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

JSON and REST<br />

The datetime(key) function used to retrieve a LocalDateTime object from JSON will by<br />

default expect a value of "Seconds since epoch". If your external webservice expects<br />

"Milliseconds since epoch" instead,<br />

you can either send datetime(key, millis = true) or configure it globally by setting<br />

JsonConfig.DefaultDateTimeMillis = true .<br />

Generating JSON objects<br />

The JsonBuilder is an abstraction over javax.json.JsonObjectBuilder that supports null<br />

values. Instead of blowing up, it silently dismisses the missing entry, which enables you to<br />

build your JSON object graph<br />

more fluently without checking for nulls.<br />

REST Client<br />

The REST Client that makes it easy to perform JSON based REST calls. The underlying<br />

HTTP engine interface has two implementations. The default uses HttpURLConnection and<br />

there is also an implementation based on Apache HttpClient. It is easy to extend the<br />

Rest.Engine to support other http client libraries if needed.<br />

To use the Apache HttpClient implementation, simply call Rest.useApacheHttpClient() in the<br />

init method of your App class and include the org.apache.httpcomponents:httpclient<br />

dependency in your project descriptor.<br />

Configuration<br />

If you mostly access the same api on every call, you can set a base uri so subsequent calls<br />

only need to include relative urls. You can configure the base url anywhere you like, but the<br />

init function of your App class is a good place to do it.<br />

class MyApp : App() {<br />

val api: Rest by inject()<br />

}<br />

init {<br />

}<br />

api.baseURI = "http://contoso.com/api"<br />

260

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!