This commit is contained in:
Ashita Prasad
2024-12-16 03:57:22 +05:30
parent 3da407b899
commit 3da6716afb
2 changed files with 8 additions and 21 deletions

View File

@@ -36,7 +36,10 @@ class HttpClientManager {
} }
void closeClient(String requestId) { void closeClient(String requestId) {
cancelRequest(requestId); if (_clients.containsKey(requestId)) {
_clients[requestId]?.close();
_clients.remove(requestId);
}
} }
bool hasActiveClient(String requestId) { bool hasActiveClient(String requestId) {

View File

@@ -16,11 +16,7 @@ Future<(HttpResponse?, Duration?, String?)> request(
SupportedUriSchemes defaultUriScheme = kDefaultUriScheme, SupportedUriSchemes defaultUriScheme = kDefaultUriScheme,
}) async { }) async {
final clientManager = HttpClientManager(); final clientManager = HttpClientManager();
http.Client? client; final client = clientManager.createClient(requestId);
if (requestId != null) {
client = clientManager.createClient(requestId);
}
(Uri?, String?) uriRec = getValidRequestUri( (Uri?, String?) uriRec = getValidRequestUri(
requestModel.url, requestModel.url,
@@ -32,13 +28,8 @@ Future<(HttpResponse?, Duration?, String?)> request(
Map<String, String> headers = requestModel.enabledHeadersMap; Map<String, String> headers = requestModel.enabledHeadersMap;
HttpResponse response; HttpResponse response;
String? body; String? body;
bool shouldCloseClient = false;
try { try {
Stopwatch stopwatch = Stopwatch()..start(); Stopwatch stopwatch = Stopwatch()..start();
if (client == null) {
client = http.Client();
shouldCloseClient = true;
}
var isMultiPartRequest = var isMultiPartRequest =
requestModel.bodyContentType == ContentType.formdata; requestModel.bodyContentType == ContentType.formdata;
if (kMethodsWithBody.contains(requestModel.method)) { if (kMethodsWithBody.contains(requestModel.method)) {
@@ -106,19 +97,12 @@ Future<(HttpResponse?, Duration?, String?)> request(
stopwatch.stop(); stopwatch.stop();
return (response, stopwatch.elapsed, null); return (response, stopwatch.elapsed, null);
} catch (e) { } catch (e) {
if (requestId != null) { if (clientManager.wasRequestCancelled(requestId)) {
if (clientManager.wasRequestCancelled(requestId)) { return (null, null, kMsgRequestCancelled);
return (null, null, kMsgRequestCancelled);
}
} }
return (null, null, e.toString()); return (null, null, e.toString());
} finally { } finally {
if (shouldCloseClient) { clientManager.closeClient(requestId);
client?.close();
}
if (requestId != null) {
clientManager.closeClient(requestId);
}
} }
} else { } else {
return (null, null, uriRec.$2); return (null, null, uriRec.$2);