post static method

Future<HttpFinchResponse> post(
  1. Uri uri, {
  2. Map<String, String>? headers,
  3. Object? body,
})

Implementation

static Future<HttpFinchResponse> post(Uri uri,
    {Map<String, String>? headers, Object? body}) async {
  var client = HttpClient();
  try {
    final response = await client.postUrl(uri).then((request) {
      headers?.forEach((key, value) {
        request.headers.set(key, value);
      });

      if (body != null) {
        if (body is String) {
          request.write(body);
        } else if (body is List<int>) {
          request.add(body);
        } else {
          request.headers.contentType = ContentType.json;
          request.write(jsonEncode(body));
        }
      }

      return request.close();
    });

    List<int> bytes = [];
    await for (var chunk in response) {
      bytes.addAll(chunk);
    }
    client.close();
    return HttpFinchResponse(
      response,
      bodyBytes: bytes,
    );
  } catch (e) {
    client.close();
    throw FinchHttpException('Failed to perform POST request: $e');
  }
}