我正在構建一個使用外部服務的應用程式,該服務提供鏈接到 PDF 檔案的 URL 串列。對于其中一些 URL,資源不存在 - 404。
我嘗試構建以下內容來遍歷 URL 串列并獲取資源是否存在,但它運行緩慢 - 每個鏈接大約每秒 100 毫秒到 500 毫秒。
任何人都有任何建議如何快速判斷資源是否存在?
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}');
}
}
}
uj5u.com熱心網友回復:
加快速度的一種簡單方法是利用異步功能。這將允許它同時運行所有請求,而不是像您的代碼顯示的那樣一次運行一個。
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}');
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/381085.html
