Created
August 22, 2021 11:46
-
-
Save matthewhartstonge/55dbb8f22936d83d6c461271f7df9f78 to your computer and use it in GitHub Desktop.
Shows the difference in boilerplate between Dart's stdlib HttpClient and package 'http/http.dart'
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
import 'dart:convert'; | |
import 'dart:io'; | |
// httpGet YOLO's a GET request to the given uri. | |
// Explosions may vary. | |
Future<dynamic> httpGet(String uri) { | |
return HttpClient(context: SecurityContext.defaultContext) | |
.getUrl(Uri.parse(uri)) | |
.then((HttpClientRequest request) { | |
// You can also do this simply as a string 'context-type' without the imported constant. | |
request.headers.add(HttpHeaders.contentTypeHeader, 'application/json'); | |
return request.close(); | |
}) | |
.then((HttpClientResponse response) async { | |
String body = await response.transform(utf8.decoder).join(); | |
if (response.statusCode >= 200 && response.statusCode < 300) { | |
print('body: $body'); | |
return jsonDecode(body); | |
} else { | |
print('status code: ${response.statusCode}'); | |
print('error body: $body'); | |
} | |
}); | |
} |
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
import 'dart:convert'; | |
import 'dart:io' show HttpHeaders; | |
import 'package:http/http.dart' as http; | |
// httpGet YOLO's a GET request to the given uri using the well respected http library. | |
// Explosions may vary. | |
Future<dynamic> httpGet(String uri) async { | |
var response = await http.get( | |
Uri.parse(uri), | |
// You can also do this simply as a string 'context-type' without the imported HttpHeaders. | |
headers: {HttpHeaders.contentTypeHeader: 'application/json'}, | |
); | |
if (response.statusCode >= 200 && response.statusCode < 300) { | |
print('body: ${response.body}'); | |
return jsonDecode(response.body); | |
} else { | |
print('status code: ${response.statusCode}'); | |
print('error body: ${response.body}'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment