【问题标题】:Error while checking if URL is exists in Flutter检查 URL 是否存在于 Flutter 中时出错
【发布时间】:2022-01-20 01:47:59
【问题描述】:

我想检查 url 是否存在。

功能:

Future _checkUrl(String url) async {
  http.Response _urlResponse =  await http.get(Uri.parse(url));
  if (_urlResponse.statusCode == 200) {
   return true;
  }
  else {
    return false;
  }
}

呼叫:

_checkUrl("https://stackoverf").then((value) => {
  print(value)
});

当我给https://fonts.google.com/?category=Sans+Serif(返回真)或https://stackoverflow.com/qu(返回假)时,它会起作用。

但是当我尝试使用无效的 https://stackoverf 时,它给了我 [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: SocketException: Failed host lookup: 'stackoverf' (OS Error: No address associated with hostname, errno = 7)

如何使 _checkUrl 在此调用中返回 false?

【问题讨论】:

  • 您是否尝试过捕获异常而不是让它不处理?
  • 参考这里:URL CHECK

标签: flutter http dart url uri


【解决方案1】:

这样的东西能满足你的需要吗?

Future<bool> _checkUrl(String url) async {
  try {
    http.Response _urlResponse =  await http.get(Uri.parse(url));
    return _urlResponse.statusCode == 200;
    // return _urlResponse.statusCode < 400 // in case you want to accept 301 for example
  } on SocketException {
    return false;
  }
}

【讨论】:

    猜你喜欢
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    相关资源
    最近更新 更多