【问题标题】:I'm getting an error when trying to pull data from OpenWeatherMap API尝试从 OpenWeatherMap API 提取数据时出现错误
【发布时间】:2021-09-18 23:11:34
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: json flutter flutter-web openweathermap dart-html


    【解决方案1】:

    试试这个

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

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

    它现在应该可以工作了。

    【讨论】:

    • 很遗憾没有。为什么这不是问题我不知道。应该是的但不是。还是同样的错误。感谢您花时间在此
    • 嗨@bearson,我已经更新了上面的答案。请检查。
    • 你是传奇
    猜你喜欢
    • 2017-01-04
    • 2019-10-15
    • 2022-01-02
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 2022-11-07
    • 2021-09-24
    • 2023-02-09
    相关资源
    最近更新 更多