postJSON method
- RequestData rd
post_JSON to our backend as the user
Implementation
Future<http.BaseResponse?> postJSON(RequestData rd) async {
var headers = {HttpHeaders.contentTypeHeader: 'application/json'};
rd.json ??= {};
rd.json!['user'] = _user?.toJson();
try {
if (rd.multipartFiles.isNotEmpty) {
http.MultipartRequest? mreq;
try {
var fullURL = Uri.parse(_baseurl + rd.route);
mreq = http.MultipartRequest('POST', fullURL)
..files.addAll(
List<http.MultipartFile>.from((await Future.wait(
rd.multipartFiles.map(
(fxfile) async {
final xfile = await fxfile;
final name = xfile.name;
var creation = 0;
creation = FileStat.statSync(xfile.path)
.changed
.toUtc()
.millisecondsSinceEpoch;
final path = xfile.path;
return http.MultipartFile.fromPath(
creation.toString(), path,
filename: name);
},
),
))
.whereType<http.MultipartFile>()),
)
..headers.addAll({HttpHeaders.authorizationHeader: _api_key})
..fields.addAll(/*flatten()*/ rd.json!.map<String, String>(
(key, value) => MapEntry(
key,
value
.toString()))); // this causes #279, but that is fixed in backend, since the formrequests fields is Map<String, String> and not Map<String, dynamic>
debugPrint("gonna send multipart-req with booty ${mreq.fields}");
var res = (rd.timeout == null)
? await _client.send(mreq)
: await _client.send(mreq).timeout(rd.timeout!);
return res;
} on SocketException catch (e) {
debugPrint('Socket-Fehler bei Multipart-Request: ${e.message}');
if (e.message.contains('Write failed') ||
e.message.contains('connection abort') ||
e.message.contains('Connection refused') ||
e.message.contains('Software caused connection abort')) {
debugPrint(
'Hintergrund-Socket-Fehler erkannt, App möglicherweise im Hintergrund');
}
rethrow;
} on Exception catch (e) {
debugPrint('multipartRequest, failed: $e');
rethrow;
}
} else {
final req =
makepost(rd.route, headers: headers, body: jsonEncode(rd.json));
try {
// Erhöhe die Robustheit des Requests speziell für Hintergrundausführung
final response = await send(
req,
timeout:
rd.timeout ?? Duration(minutes: 2), // Längerer Standard-Timeout
returnsBinary: rd.returnsBinary,
);
return response;
} on SocketException catch (e) {
debugPrint('Socket-Fehler bei HTTP-Request: ${e.message}');
if (e.message.contains('Write failed') ||
e.message.contains('connection abort') ||
e.message.contains('Connection refused') ||
e.message.contains('Software caused connection abort')) {
debugPrint(
'Hintergrund-Socket-Fehler erkannt, App möglicherweise im Hintergrund');
}
rethrow;
} catch (e) {
debugPrint('request failed: $e');
rethrow;
}
}
} catch (e) {
debugPrint("request failed, cause : $e");
return null;
}
}