json - 我在尝试从 OpenWeatherMap API 提取数据时遇到错误

标签 json flutter flutter-web openweathermap dart-html

我目前正在从 Udemy course 学习 Flutter (第 146 课)。 在本课中,我需要使用 http package 中的 get 方法。 。这是我正在使用的代码:

class Location {
  String apiKey = 'e20c545d412bb5ecc1c27b9b6afd5d37';

  Future<void> getCurrentLocation() async {
    Position position = await Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.low,
      forceAndroidLocationManager: true,
    );
    
    var data =  await get(Uri.https('api.openweathermap.org',
        '/data/2.5/weather?lat=${position.latitude}}&lon=${position.longitude}&appid=$apiKey'));
    print(data.body);
    
  }
}

这是我得到的错误:

I/flutter ( 9366): {"cod":401, "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."}

到目前为止我尝试过的事情:

  1. 我尝试在网络浏览器上使用该 key 。它在那里工作。我可以毫无问题地获取 JSON 数据。因此 key 处于事件状态。
  2. 我尝试更改代码,将其放入单独的 dart 文件中。没有变化。

我认为问题是,我无法将 key 发送到 API。或者存在某种我看不到的语法或逻辑错误。所以 API 给了我一个关于 key 的错误。因为我的代码没有发送适当的信息。

由于我无法解决这个问题,所以我在类(class)中无法取得任何进展。这是我尝试解决此问题的第三天。我真的很沮丧。我希望有人可以帮助我。

最佳答案

试试这个

var data =  await get(Uri.parse('https://api.openweathermap.org'+
    '/data/2.5/weather?lat=${position.latitude}&lon=${position.longitude}&appid=$apiKey'));

我刚刚在我的机器上测试了它,它工作正常

现在应该可以工作了。

关于json - 我在尝试从 OpenWeatherMap API 提取数据时遇到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68302409/

相关文章:

Flutter - 在 Visual Studio Code 中快速选择整个小部件的快捷键

带有 Hive 数据库的 Flutter Web

flutter - 在 Flutter Web 上无法选择文本 [稳定]

java - 如何使用 GSON 迭代 JSON 数组并从中提取每个 JSON 对象?

Python 推特流时间线

javascript - Hello World - Backbone + Firebase + Backfire

dart - Flutter 区 block 模式 : Update BloC Streams Based Another BloC's Stream

flutter - 如何转换 HH :MM:SS STRING format to an integer in minutes?

android - Volley 解析给出错误

flutter - Gif 没有得到动画 flutter web