send method
Implementation
@override
Future<ResponseOptions> send(RequestOptions options) async {
if (options.cancelToken?.isCancelled == true) {
throw RequestCancelledException(options.cancelToken!.reason!);
}
final req = await _client.openUrl(options.method, options.uri);
// headers
options.headers.forEach(req.headers.set);
// body
if (options.body != null) {
if (options.body is String) {
final s = options.body as String;
req.add(utf8.encode(s));
} else if (options.body is List<int>) {
req.add(options.body as List<int>);
} else {
if (!req.headers.value(HttpHeaders.contentTypeHeader)!.contains("application/json") ?? true) {
req.headers.set(HttpHeaders.contentTypeHeader, "application/json");
}
req.add(utf8.encode(jsonEncode(options.body)));
}
}
// timeout
Future<HttpClientResponse> doSend() async {
if (options.cancelToken?.isCancelled == true) {
req.abort();
throw RequestCancelledException(options.cancelToken!.reason!);
}
return await req.close();
}
final Future<HttpClientResponse> fut = (options.timeout == null)
? doSend()
: doSend().timeout(options.timeout!, onTimeout: () {
req.abort();
throw QuickTimeoutException();
});
late HttpClientResponse resp;
try {
resp = await fut;
} on RequestCancelledException {
rethrow;
} on QuickTimeoutException {
rethrow;
} catch (e) {
throw NetworkException(e.toString());
}
// cancel kontrol (response aşamasında)
if (options.cancelToken?.isCancelled == true) {
// DOĞRU
try {
final sock = await resp.detachSocket();
sock.destroy();
} catch (_) {}
throw RequestCancelledException(options.cancelToken!.reason!);
}
final bytes = await resp.fold<List<int>>(<int>[], (b, d) => b..addAll(d));
final bodyStr = bytes.isEmpty ? "" : utf8.decode(bytes, allowMalformed: true);
final contentType = resp.headers.contentType?.mimeType ?? '';
dynamic data;
if (contentType.contains('application/json')) {
try {
data = jsonDecode(bodyStr);
} catch (_) {
data = bodyStr;
}
} else {
data = bodyStr.isEmpty ? null : bodyStr;
}
return ResponseOptions(
statusCode: resp.statusCode,
data: data,
requestOptions: options,
);
}