I want to check that the url exists or not.
Fuction:
Future _checkUrl(String url) async {
http.Response _urlResponse = await http.get(Uri.parse(url));
if (_urlResponse.statusCode == 200) {
return true;
}
else {
return false;
}
}
Call:
_checkUrl("https://stackoverf").then((value) => {
print(value)
});
It works when I give https://fonts.google.com/?category=Sans Serif
(returns true) or https://stackoverflow.com/qu
(returns false).
But when I try with https://stackoverf
which is not valid, it gives me [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)
.
How to make _checkUrl
returns false with this call?
CodePudding user response:
Would something like this work for what you want?
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;
}
}