56 lines
2.1 KiB
Dart
56 lines
2.1 KiB
Dart
// * Service for handling HTTP requests to the backend API
|
|
// * Features:
|
|
// * - Support for camera trap and excursion data endpoints
|
|
// * - Configurable timeouts
|
|
// * - Error handling
|
|
// * - JSON data formatting
|
|
|
|
import 'dart:convert';
|
|
import 'package:dio/dio.dart';
|
|
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
/// Service class for making HTTP requests to the backend
|
|
/// Handles both camera trap and excursion data submissions
|
|
class HttpRequestService {
|
|
/// Send data to the appropriate backend endpoint
|
|
/// @param saveDataMap Optional map of data to send
|
|
/// @param saveDataString Optional string of data to send
|
|
/// @return Future[int] HTTP status code of the response
|
|
static Future<int> httpRequest({Map<String, String>? saveDataMap, String? saveDataString}) async {
|
|
// print(jsonEncode(place));
|
|
|
|
final dio = Dio();
|
|
final SharedPreferences prefs = await SharedPreferences.getInstance();
|
|
|
|
dio.options
|
|
..connectTimeout = const Duration(seconds: 5)
|
|
..receiveTimeout = const Duration(seconds: 5)
|
|
..responseType = ResponseType.plain;
|
|
Response response =
|
|
Response(requestOptions: RequestOptions(path: ''), statusCode: 400);
|
|
|
|
|
|
try {
|
|
// Choose endpoint based on data type (camera trap vs excursion)
|
|
if (saveDataMap != null && saveDataMap.containsKey("CID") || saveDataString != null && saveDataString.contains("CID")) {
|
|
// write username in Sent field
|
|
if (saveDataMap != null) {
|
|
saveDataMap["Sent"] = prefs.getString("addresse1") ?? "";
|
|
} else if (saveDataString != null){
|
|
saveDataString.replaceAll("\"Sent\": \"\"", "\"Sent\": \"${prefs.getString("addresse1")}\"");
|
|
}
|
|
|
|
response = await dio.post(prefs.getString('fotofallenApiAddress') ?? "",
|
|
data: saveDataMap == null ? saveDataString : jsonEncode(saveDataMap));
|
|
} else {
|
|
response = await dio.post(prefs.getString('exkursionenApiAddress') ?? "",
|
|
data: saveDataMap == null ? saveDataString : jsonEncode(saveDataMap));
|
|
}
|
|
return response.statusCode!;
|
|
} on DioException {
|
|
return response.statusCode ?? 400;
|
|
}
|
|
}
|
|
}
|