Flutter HTTP请求中API Key无效错误的排查与解决
问题分析与解决方案
错误原因
- 协议不匹配:代码中使用
Uri.http生成HTTP协议的请求地址,但WeatherAPI仅支持HTTPS访问。浏览器用HTTPS能正常请求,而代码里的HTTP请求会被服务端重定向,重定向过程中查询参数(包括API Key)可能丢失,从而触发API key is invalid or not provided错误。 - 参数传递方式错误:将查询参数直接拼接在
unencodedPath中,不符合Uri.http/Uri.https的使用规范,即使无特殊字符,也可能因路径编码逻辑导致参数无法被服务端正确解析。
修复方案
方案一:使用Uri.https分离路径与查询参数(推荐)
这种方式自动处理参数编码,且严格遵循HTTPS协议要求:
import 'dart:convert'; import "package:http/http.dart" as http; String authority = "api.weatherapi.com"; String apiKey = "bc4512ff6799474cbcc114118222908"; String query = "london"; Future getWeatherData() async { var uri = Uri.https( authority, "v1/forecast.json", { "key": apiKey, "q": query, "days": "10", "aqi": "yes", "alerts": "yes" }, ); var response = await http.get(uri); var jsonData = jsonDecode(response.body); print(jsonData); }
方案二:直接使用完整HTTPS URL字符串
若需快速验证,可直接拼接符合要求的HTTPS URL:
import 'dart:convert'; import "package:http/http.dart" as http; String apiKey = "bc4512ff6799474cbcc114118222908"; String query = "london"; String fullUrl = "https://api.weatherapi.com/v1/forecast.json?key=$apiKey&q=$query&days=10&aqi=yes&alerts=yes"; Future getWeatherData() async { var response = await http.get(Uri.parse(fullUrl)); var jsonData = jsonDecode(response.body); print(jsonData); }
验证说明
修改后重新执行代码,即可正常获取WeatherAPI的返回数据。核心是确保请求使用HTTPS协议,且参数传递符合Uri构造器规范。
内容的提问来源于stack exchange,提问作者Ayan Dasgupta
相关产品推荐
相关产品推荐

