Created
July 22, 2021 18:47
-
-
Save soeleman/134a2b7903ef84bbb5f757e9fbab713c to your computer and use it in GitHub Desktop.
Sample HttpClient Flutter
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'; | |
class ApiProvider { | |
final Uri uri; | |
final HttpClient _client = HttpClient(); | |
ApiProvider(this.uri); | |
Future<String> makeGetRequest() async { | |
final request = await _client.getUrl(uri) | |
..headers.contentType = ContentType.json; | |
final response = await request.close(); | |
if (response.statusCode != 200) { | |
throw ApiException( | |
error: 'Status code ${response.statusCode}', | |
description: 'Received ${response.headers}'); | |
} | |
var raw = ''; | |
await response | |
.transform(Utf8Decoder(allowMalformed: true)) | |
.forEach((element) => raw += element); | |
return raw; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment