如何检查 url link 是否存在并在 flutter 中获取 statusCode?

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

我正在尝试使用 statusCode == 200 检查 url 是否存在,但是当我尝试使用 await http.get(url) 时,它不起作用。我收到这个错误 XMLHttpRequest error

flutter 版本

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');
  }
}

并调用 getStatusCode()

这很可能是跨源请求问题,也称为 CORS。您正在 运行 网络上查看此内容。如果你在 android 或 iOS 上 运行 就没问题,但在网络中你不能只向另一个站点发出网络请求,而另一个站点不允许你这样做所以通过遵循一些关于 CORS 的协议。

出现问题是因为您的网页所在的域 运行 最有可能是本地主机不是 googl.com,所以它是不同的来源。

此外,200 http 代码用于检查请求是否成功,这是正确的术语,记住这一点很重要。

代码看起来不错,也很实用。如果没有互联网,它将抛出异常 Unhandled Exception: SocketException。否则它会打印 exists.