sendRequest method
Helper function for constructing, validating and handling various HTTP requests for capture.
Implementation
Future sendRequest(JRpcRequest request) async {
String uriString = this.host ?? '';
final uri = Uri.parse(uriString);
final headers = {'Content-Type': 'application/json'};
// ignore: prefer_function_declarations_over_variables
Future helper(JRpcRequest jsonRpc) async {
try {
String jsonRpcString = json.encode(jsonRpc.toJson());
logger!.log(jsonRpc.method.toString() + ' =>', jsonRpcString);
Response res = await post(uri, headers: headers, body: jsonRpcString);
dynamic err = json.decode(res.body)['error'];
print(err);
if (err != null) {
throw CaptureException(err['code'], err['message'] ?? 'no message');
} else {
return JRpcResponse(1, res.body);
}
} on CaptureException catch (err) {
rethrow;
} catch (err) {
throw CaptureException(SktErrors.ESKT_COMMUNICATIONERROR, 'There was an error during communication.', err.toString());
}
}
JRpcResponse response = await helper(request);
logger!.log(
request.method.toString() + ' <=', json.encode(response.toString()));
if (request.method == 'openclient') {
/// we want to start the web service here if we can
this.openWebSocket((event) {
if (response.runtimeType == JRpcResponse) {
/// send a waitForEvent
if (response.result != null) {
dynamic r = json.decode(response.result);
int handle = r['result']['handle'];
Map<String, dynamic> waitForEvent =
JRpcRequest(1, 'waitforcaptureevent', Params(handle)).toJson();
String waitForEventString = json.encode(waitForEvent);
//use sink.add to send data to server
this.websocket!.sink.add(waitForEventString);
}
return;
}
});
}
return response;
}