Home > Enterprise >  How do I check whether an url link exists and get statusCode in flutter?
How do I check whether an url link exists and get statusCode in flutter?

Time:09-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

flutter version

2.5.0

package

http: ^0.13.3

My code

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()

CodePudding user response:

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.

CodePudding user response:

The code looks good and also functional. If there is no internet it will throw exception Unhandled Exception: SocketException. else it will print exists.

  • Related