mirror of
https://gitlab.com/comunic/comunicmobile
synced 2025-09-19 05:48:54 +00:00
Use http package for requests
This commit is contained in:
@@ -5,14 +5,13 @@ import 'package:comunic/helpers/account_credentials_helper.dart';
|
||||
import 'package:comunic/models/api_request.dart';
|
||||
import 'package:comunic/models/api_response.dart';
|
||||
import 'package:comunic/models/config.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
/// API Helper
|
||||
///
|
||||
/// @author Pierre HUBERT
|
||||
|
||||
class APIHelper {
|
||||
final _httpClient = HttpClient();
|
||||
|
||||
/// Execute a [request] on the server and returns a [APIResponse]
|
||||
///
|
||||
/// This method should never throw but the response code of the [APIResponse]
|
||||
@@ -31,16 +30,6 @@ class APIHelper {
|
||||
request.addString("userToken2", tokens.tokenTwo);
|
||||
}
|
||||
|
||||
// Prepare request body
|
||||
String requestBody = "";
|
||||
request.args.forEach((key, value) => requestBody +=
|
||||
Uri.encodeQueryComponent(key) +
|
||||
"=" +
|
||||
Uri.encodeQueryComponent(value) +
|
||||
"&");
|
||||
|
||||
List<int> bodyBytes = utf8.encode(requestBody);
|
||||
|
||||
// Determine server URL
|
||||
final path = config().apiServerUri + request.uri;
|
||||
Uri url;
|
||||
@@ -49,22 +38,16 @@ class APIHelper {
|
||||
else
|
||||
url = Uri.https(config().apiServerName, path);
|
||||
|
||||
//Connect to server
|
||||
final connection = await _httpClient.postUrl(url);
|
||||
connection.headers.set("Content-Length", bodyBytes.length.toString());
|
||||
connection.headers
|
||||
.set("Content-Type", "application/x-www-form-urlencoded");
|
||||
connection.add(bodyBytes);
|
||||
|
||||
final response = await connection.close();
|
||||
final response = await http.post(
|
||||
url.toString(),
|
||||
body: request.args,
|
||||
encoding: utf8
|
||||
);
|
||||
|
||||
if (response.statusCode != HttpStatus.ok)
|
||||
return APIResponse(response.statusCode, null);
|
||||
|
||||
//Save & return response
|
||||
final responseBody = await response.transform(utf8.decoder).join();
|
||||
|
||||
return APIResponse(response.statusCode, responseBody);
|
||||
return APIResponse(response.statusCode, utf8.decode(response.bodyBytes));
|
||||
} on Exception catch (e) {
|
||||
print(e.toString());
|
||||
print("Could not execute a request!");
|
||||
|
Reference in New Issue
Block a user