Asynchronous calls are now available in the Hubitat Elevation system.
The following methods are available:
void asynchttpGet(String callbackMethod, Map params, Map data = null)
void asynchttpPost(String callbackMethod, Map params, Map data = null)
void asynchttpPut(String callbackMethod, Map params, Map data = null)
void asynchttpDelete(String callbackMethod, Map params, Map data = null)
void asynchttpPatch(String callbackMethod, Map params, Map data = null)
void asynchttpHead(String callbackMethod, Map params, Map data = null)
Possible values for params are as such:
name | value |
---|---|
uri (required) | A URI or URL of the endpoint to send a request to |
path | Request path that is merged with the URI. |
query | Map of URL query parameters. |
headers | Map of HTTP headers. |
requestContentType | The value of the Content-Type request header. Defaults to 'application/json'. |
contentType | The value of the Accept request header. Defaults to the value of the requestContentType parameter if not specified. |
body | The request body to send. Can be a string, or if the requestContentType is "application/json", a Map or List (will be serialized to JSON). |
The callback method should be defined as such:
def processCallBack(response, data) {
}
the name of the callback method can be whatever you choose, just pass it's name to the async method and the system will call it with the results of the http call and also any data you wish to pass to the method.
The first parameter to the callback method (response) is an AsyncResponse object. The methods available on this object are as follows:
Method | Description |
---|---|
int getStatus() | The status code of the response from the call |
Map<String, String> getHeaders() | A map of the headers returned from the call |
String getData() | String value of the response body from the call |
String getErrorData() | |
String getErrorJson() | |
String getErrorMessage() | |
GPathResult getErrorXml() | |
Object getJson() | |
GPathResult getXml() | |
boolean hasError() |
Below is an example of code which would be used to send a POST to a server and the callback method to process the response:
def sendAsynchttpPost() {
def postParams = [
uri: "http://httpbin.org/post",
requestContentType: 'application/json',
contentType: 'application/json',
headers: ['CustomHeader':'CustomHeaderValue'],
body : ["name": "value"]
]
asynchttpPost('myCallbackMethod', postParams, [dataitem1: "datavalue1"])
}
def myCallbackMethod(response, data) {
if(data["dataitem1"] == "datavalue1")
log.debug "data was passed successfully"
log.debug "status of post call is: ${response.status}"
}