You need to enable JavaScript to run this app. 调用WeatherStack API返回null?附完整代码求排查
优惠活动
大模型
产品
解决方案
定价
更多

调用WeatherStack API返回null?附完整代码求排查

问题排查及修复方案

1. API密钥参数名错误

你在请求拦截器里添加的密钥参数名是key,但WeatherStack官方要求的身份验证参数名是*access_key*,这是最核心的报错原因。
修改WeatherStackApiService.kt里的拦截器代码:
把

.addQueryParameter("key", API_KEY)

替换为

.addQueryParameter("access_key", API_KEY)

2. 明文HTTP请求适配(安卓9+)

你使用的是HTTP协议,安卓9及以上系统默认禁止明文流量请求,需要额外配置:

  • 在res/xml目录下新建network_security_config.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">api.weatherstack.com</domain>
    </domain-config>
</network-security-config>
  • 然后在AndroidManifest.xml的application标签里添加属性:
android:networkSecurityConfig="@xml/network_security_config"

3. 数据类字段类型校验

WeatherStack返回的precip(降水量)字段为浮点型数值,你现在定义成了Int类型,Gson解析时会失败导致返回null,建议把CurrentWeatherEntry.kt里的precip字段类型修改为Double:

val precip: Double,

4. 补充异常捕获

你现在的协程代码没有加异常捕获,请求失败会直接崩溃,建议修改协程代码:

GlobalScope.launch(Dispatchers.Main) {
    try {
        val currentWeatherResponse = apiService.getCurrentWeatherAsync("London").await()
        textView.text = currentWeatherResponse.toString()
    } catch (e: Exception) {
        textView.text = "请求失败:${e.message}"
        e.printStackTrace()
    }
}

内容的提问来源于stack exchange,提问作者waqas093456

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 08:06:04