json - 尝试从 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。"}
到目前为止我尝试过的事情:
- 我试图在网络浏览器上使用密钥。它在那里工作。我可以毫无问题地获取 JSON 数据。所以钥匙是活动的。
- 我试图更改代码,将其放入单独的 dart 文件中。没有变化。
我认为问题是,我无法将密钥发送到 API。或者有某种我看不到的语法或逻辑错误。所以 API 给了我一个关于密钥的错误。由于我的代码没有发送适当的信息。
我无法在课程中取得任何进展,因为我无法解决这个问题。这是我尝试解决此问题的第三天。我真的很沮丧。我希望有人可以在这里帮助我。
解决方案
尝试这个
var data = await get(Uri.parse('https://api.openweathermap.org'+
'/data/2.5/weather?lat=${position.latitude}&lon=${position.longitude}&appid=$apiKey'));
我刚刚在我的机器上测试了它并且工作正常
它现在应该可以工作了。
推荐阅读
- json - 将 json 对象转换为字符串以将它们存储在 firestore 数据库中
- c - fgets 想要输入两次
- python - 当我尝试使用 coremltool 将我的 h5 文件转换为 mlmodel 时,我不断收到此错误 ValueError: Unknown initializer: GlorotUniform
- python - 无法让 sqlalchemy 和 pandas (to_sql) 将数据帧索引日期写入 MySQL 数据库
- python - 如何从字典列表中删除文本
- python - 如何在模型内部改变 Keras 模型的输出阈值?
- python - 将参数从 locust 用户传递到任务集参数的最佳方法是什么,其中任务集已被分隔到不同的文件中?
- flutter - 由于 Flutter 代码混淆,创建失败
- python - 视频比音频电影快得多
- c++ - 获取给定问题的 SIGSEGV(分段错误)。(寻找通用树的 LCA)