createRequest method
Implementation
Future<HttpClientRequest> createRequest(SendContext info) async {
var url = info.url ?? info.uri?.toString();
var method = info.method;
var request = info.request;
var body = info.body ?? request;
var args = info.args;
if (url == null || url == '') {
var bodyNotRequestDto = info.request != null && info.body != null;
if (bodyNotRequestDto) {
url = combinePaths([this.replyBaseUrl, nameOf(request)]);
url = appendQueryString(url, toMap(request));
} else {
url = createUrlFromDto(method, request);
}
}
if (url == null) throw ArgumentError.notNull('url');
if (args != null) url = appendQueryString(url, args);
String? bodyStr;
if (hasRequestBody(method)) {
if (body is String) {
bodyStr = body;
} else {
bodyStr = json.encode(body);
}
}
HttpClientRequest? req;
Exception? firstEx;
var uri = info.uri ?? createUri(url);
for (var attempt = 0; attempt < maxRetries; attempt++) {
try {
req = await client.openUrl(method, uri!);
break;
} on Exception catch (e, trace) {
Log.debug("createRequest(): $e\n$trace");
if (firstEx == null) {
firstEx = e;
}
}
}
if (req == null) throw firstEx!;
if (bearerToken != null)
req.headers
.add(HttpHeaders.authorizationHeader, 'Bearer ' + bearerToken!);
else if (userName != null)
req.headers.add(HttpHeaders.authorizationHeader,
'Basic ' + base64.encode(utf8.encode('$userName:$password')));
req.cookies.addAll(this.cookies!);
req.headers.chunkedTransferEncoding = false;
headers.forEach((key, val) {
if (key == HttpHeaders.contentTypeHeader) {
var parts = val.split("/");
req!.headers.contentType = ContentType(parts[0], parts[1]);
} else {
req!.headers.add(key, val);
}
});
if (bodyStr != null) {
req.headers.contentType = ContentType.json;
// var bodyBytes = bodyStr != null ? utf8.encode(bodyStr) : null;
req.contentLength = utf8.encode(bodyStr).length;
}
if (info.requestFilter != null) {
info.requestFilter!(req);
}
if (requestFilter != null) {
requestFilter!(req);
}
if (globalRequestFilter != null) {
globalRequestFilter!(req);
}
if (bodyStr != null) {
req.write(bodyStr);
}
return req;
}