我目前正在从 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."}
到目前为止我尝试过的事情:
- 我尝试在网络浏览器上使用该 key 。它在那里工作。我可以毫无问题地获取 JSON 数据。因此 key 处于事件状态。
- 我尝试更改代码,将其放入单独的 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/