jsonRequest method

Future<Map<String, dynamic>> jsonRequest(
  1. String url, {
  2. bool followRedirects = true,
  3. Duration? timeout,
  4. Map<String, String> headers = const {"Accept" : "application/json"},
})

make a get request to the given url

Implementation

Future<Map<String, dynamic>> jsonRequest(
  String url, {
  bool followRedirects = true,
  Duration? timeout,
  Map<String, String> headers = const {"Accept": "application/json"},
}) async {
  final uri = Uri.parse(url).replace(scheme: 'https');

  final http.Response response;
  if (followRedirects && timeout == null) {
    response = await _client.get(uri, headers: headers);
  } else {
    final abort = Completer<void>();
    final timer = timeout == null ? null : Timer(timeout, abort.complete);
    final request =
        http.AbortableRequest('GET', uri, abortTrigger: abort.future)
          ..headers.addAll(headers)
          ..followRedirects = followRedirects;
    try {
      response = await http.Response.fromStream(await _client.send(request));
    } finally {
      timer?.cancel();
    }
  }

  if (!_isSuccessStatus(response.statusCode)) {
    throw HttpRequestException(
      statusCode: response.statusCode,
      body: response.body,
      url: url,
    );
  }
  // JSON is UTF-8 (RFC 8259); `body` would fall back to latin1 for media
  // types such as application/nostr+json that carry no charset.
  return jsonDecode(utf8.decode(response.bodyBytes));
}