Reputation: 27
I'm trying to check whether an url exists by using statusCode == 200
but when I try to use await http.get(url)
, it didn't work. I got this error XMLHttpRequest error
2.5.0
http: ^0.13.3
import 'package:http/http.dart' as http;
final url = Uri.parse('https://www.google.com');
void getStatusCode() async {
http.Response response = await http.get(url);
if (response.statusCode == 200) {
print('exists');
} else {
print('not exists');
}
}
and call getStatusCode()
Upvotes: 1
Views: 2015
Reputation: 233
The code looks good and also functional. If there is no internet it will throw exception Unhandled Exception: SocketException
. else it will print exists
.
Upvotes: 2
Reputation: 828
This is most likely a cross origin request problem otherwise known as CORS. You are running this on the web. If you were to run it on android or iOS you would be fine, but in web you can't just make a network request to another site without that other site allowing you to do so via following some protocols regarding CORS.
The problem happens because the domain that your webpage is running on which is most likely localhost is not googl.com so it's a different origin.
Also the 200 http code is for checking if a request is successful that is the right terminology it's important to keep that in mind.
Upvotes: 3