I am building an app that uses an external service that supplies a list of URL's that link to PDF documents. For some of these URL's the resource does not exist - 404.
I tried building the following to loop through the list of URL's and get whether the resource exists or not, but it runs slowly - about 100ms to 500ms second per link.
Anyone have any advice how to quickly tell if the resource exists or not?
var client = http.Client();
for (Article article in articles) {
if (article.downloadUrl != null) {
Uri url = Uri.parse(article.downloadUrl!);
http.Response _response = await client.head(url);
if (_response.statusCode == 404) {
print('Bad - ${article.downloadUrl}');
} else {
print('Good - ${article.downloadUrl}');
}
}
}
CodePudding user response:
A simple way to speed it up would be to take advantage of the async functionality. This would allow it to run all the requests at the same time versus one at a time as your code shows.
var client = http.Client();
List<Future> futures = [];
for (Article article in articles) {
if (article.downloadUrl != null) {
Uri url = Uri.parse(article.downloadUrl!);
futures.add(isValidLink(url));
}
}
await Futures.wait(futures);
Future<void> isValidLink(Uri url) async {
http.Response _response = await client.head(url);
if (_response.statusCode == 404) {
print('Bad - ${article.downloadUrl}');
} else {
print('Good - ${article.downloadUrl}');
}
}