send method
Send a request. path can have a query, eg. /users?page=2.
A String or List<int> body is sent as it is. Any other body
(eg. a Map) is sent as JSON, with Content-Type: application/json.
Redirects are not followed, so you can check them.
Implementation
Future<TestResponse> send(
String method,
String path, {
Object? body,
Map<String, String>? headers,
}) async {
HttpClientRequest request = await _http.openUrl(
method,
baseUri.resolve(path),
);
request.followRedirects = false;
List<int>? bytes;
if (body is List<int>) {
bytes = body;
} else if (body is String) {
bytes = utf8.encode(body);
} else if (body != null) {
bytes = utf8.encode(jsonEncode(body));
request.headers.contentType = ContentType.json;
}
Map<String, String> all = <String, String>{...this.headers, ...?headers};
Map<String, String>? jar = _jar;
if (jar != null) _addJar(jar, method, all);
for (MapEntry<String, String> header in all.entries) {
request.headers.set(header.key, header.value);
}
if (bytes != null) {
request.contentLength = bytes.length;
request.add(bytes);
}
HttpClientResponse response = await request.close();
BytesBuilder data = BytesBuilder(copy: false);
await for (List<int> chunk in response) {
data.add(chunk);
}
if (jar != null) _keep(jar, response.cookies);
Map<String, String> found = <String, String>{};
response.headers.forEach((String name, List<String> values) {
found[name.toLowerCase()] = values.join(', ');
});
return TestResponse(
response.statusCode,
found,
data.takeBytes(),
cookies: <String, String>{
for (Cookie cookie in response.cookies) cookie.name: cookie.value,
},
);
}