-
Notifications
You must be signed in to change notification settings - Fork 64
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
dart: add a remote lib to handle http requests
- Loading branch information
1 parent
097ee79
commit 96ebd0b
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |