首页 > 解决方案 > 尝试从 OpenWeatherMap API 提取数据时出现错误

问题描述

我目前正在从Udemy 课程(第 146 课)中学习 Flutter。在本课中,我需要使用http 包中的 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": "无效的 API 密钥。有关更多信息,请参阅http://openweathermap.org/faq#error401。"}

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

  1. 我试图在网络浏览器上使用密钥。它在那里工作。我可以毫无问题地获取 JSON 数据。所以钥匙是活动的。
  2. 我试图更改代码,将其放入单独的 dart 文件中。没有变化。

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

我无法在课程中取得任何进展,因为我无法解决这个问题。这是我尝试解决此问题的第三天。我真的很沮丧。我希望有人可以在这里帮助我。

标签: jsonflutterflutter-webopenweathermapdart-html

解决方案


尝试这个

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

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

它现在应该可以工作了。


推荐阅读