post method

Future<Map<String, dynamic>> post(
  1. String path,
  2. Map<String, dynamic> body
)

Implementation

Future<Map<String, dynamic>> post(
  String path,
  Map<String, dynamic> body,
) async {
  await _ensureAuthenticated();

  final url = (_areaDomain ?? baseUrl) + path;

  // Convert all values to strings for form-encoded data
  final stringBody = <String, String>{'accessToken': _accessToken!};

  for (final entry in body.entries) {
    stringBody[entry.key] = entry.value.toString();
  }

  final response = await _http.post(
    Uri.parse(url),
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body: stringBody,
  );

  if (response.statusCode == 200) {
    final data = jsonDecode(response.body);
    if (data['code'] == '200') {
      return data; // Or data['data'] depending on API structure
    } else {
      // Handle authentication errors for provided tokens
      if (data['code'] == '10001' || data['code'] == '10002') {
        if (_hasProvidedAccessToken) {
          throw EzvizAuthException(
            'Provided access token is invalid or expired: ${data['msg']}',
            code: data['code'],
          );
        } else {
          // Try to re-authenticate for API-obtained tokens
          await _authenticate();
          return post(path, body); // Retry the request
        }
      }
      throw EzvizApiException(
        'API Error: ${data['msg']}',
        code: data['code'],
      );
    }
  } else {
    throw EzvizApiException(
      'API request failed with status: ${response.statusCode}',
    );
  }
}