Skip to content

Commit

Permalink
dart: add a remote lib to handle http requests
Browse files Browse the repository at this point in the history
  • Loading branch information
dna2github committed Mar 29, 2024
1 parent 097ee79 commit 96ebd0b
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions lib/util/remote.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import 'dart:convert';
import 'dart:io';

Future<Map<String, dynamic>?> remoteGet(String url) async {
HttpClient client = HttpClient();
try {
final req = await client.getUrl(Uri.parse(url));
final response = await req.close();
if (response.statusCode / 200 == 2) {
final stream = await response.transform(utf8.decoder).toList();
final ret = jsonDecode(stream.first) as Map<String, dynamic>;
return ret;
}
throw "request failure";
} catch (e) {
return null;
} finally {
client.close();
}
}

Future<Map<String, dynamic>?> remotePost(String url, Map<String, dynamic> data) async {
HttpClient client = HttpClient();
try {
final req = await client.postUrl(Uri.parse(url));
req.headers.set("Content-Type", "application/json");
req.write(data);
final response = await req.close();
if (response.statusCode / 200 == 2) {
final stream = await response.transform(utf8.decoder).toList();
final ret = jsonDecode(stream.first) as Map<String, dynamic>;
return ret;
}
throw "request failure";
} catch (e) {
return null;
} finally {
client.close();
}
}

0 comments on commit 96ebd0b

Please sign in to comment.