send method
Sends an HTTP request and asynchronously returns the response.
Implementers should call BaseRequest.finalize to get the body of the
request as a ByteStream. They shouldn't make any assumptions about the
state of the stream; it could have data written to it asynchronously at a
later point, or it could already be closed when it's returned. Any
internal HTTP errors should be wrapped as ClientExceptions.
Implementation
@override
Future<http.StreamedResponse> send(http.BaseRequest request) async {
Future<void>? abort = request is http.Abortable
? request.abortTrigger
: null;
if (abort != null) {
// a trigger that is complete now: the request must not go out
bool aborted = false;
unawaited(abort.then((_) => aborted = true));
await null;
if (aborted) throw http.RequestAbortedException(request.url);
}
int? length = request.contentLength;
http.ByteStream body = request.finalize();
// the native client sets these two itself
Map<String, String> headers = <String, String>{};
for (MapEntry<String, String> header in request.headers.entries) {
String name = header.key.toLowerCase();
if (name == 'content-length' || name == 'transfer-encoding') continue;
headers[header.key] = header.value;
}
// No body: the native client then follows redirects and can send the
// request again. It sends `content-length: 0` for POST, PUT and PATCH.
bool empty = length == 0;
if (empty) body.drain<void>().ignore();
DoxHttpClientStreamedResponse res;
try {
res = await _client.sendStreamed(
request.method,
request.url,
headers: headers,
body: empty ? null : body,
contentLength: empty ? null : length,
followRedirects: request.followRedirects,
abort: abort,
);
} on DoxHttpClientException catch (e) {
throw _failure(e);
}
String? size = res.headers['content-length'];
return http.StreamedResponse(
res.body.transform(
StreamTransformer<Uint8List, List<int>>.fromHandlers(
handleError:
(Object error, StackTrace trace, EventSink<List<int>> sink) {
sink.addError(
error is DoxHttpClientException ? _failure(error) : error,
trace,
);
},
),
),
res.statusCode,
contentLength: size == null ? null : int.tryParse(size),
request: request,
headers: res.headers,
isRedirect:
_redirects.contains(res.statusCode) &&
res.headers.containsKey('location'),
);
}