You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Retrofit GET请求无响应问题求助

问题分析与解决方案

1. 补充错误日志,定位核心问题

你的代码里onFailure方法是空实现,完全无法获取请求失败的原因;onResponse中也未判断响应是否成功,直接强制解包response.body()!!极易触发空指针异常。先完善这部分代码,才能拿到有效错误信息:

call?.enqueue(object : Callback<Example?> {
    override fun onResponse(call: Call<Example?>?, response: Response<Example?>) {
        try {
            // 先判断响应是否成功
            if (response.isSuccessful) {
                val weatherData = response.body()
                weatherData?.let { data ->
                    Log.i("TAG", data.main.toString())
                    tempTemp = data.main.temperature.toString()
                    cityText.text = tempName
                    currentTemperatureText.text = tempTemp
                    // 注意:OpenWeatherAPI的weather字段是数组,不是单个对象
                    data.weather.firstOrNull()?.let { weather ->
                        descriptionText.text = weather.description
                        tempIcon = weather.icon
                        setIcon()
                    } ?: Log.w("TAG", "未获取到天气描述数据")
                } ?: Log.w("TAG", "响应体为空")
            } else {
                // 打印响应错误信息,比如HTTP状态码、错误内容
                Log.e("TAG", "请求失败,状态码:${response.code()},错误信息:${response.errorBody()?.string()}")
            }
        } catch (e: Exception) {
            Log.e("TAG", "解析数据失败", e)
        }
    }

    override fun onFailure(call: Call<Example?>?, t: Throwable?) {
        // 打印请求失败的异常信息
        t?.let {
            Log.e("TAG", "请求网络失败", it)
        }
    }
})

2. 检查数据模型Example是否匹配OpenWeatherAPI响应结构

OpenWeatherAPI的返回结构中,weather是数组类型(即使仅返回一条天气数据),如果你的Example类里将weather定义为单个对象而非List<Weather>,会直接导致解析失败,进而出现response.body()为空或崩溃。

正确的模型结构示例(简化版):

data class Example(
    val main: Main,
    val weather: List<Weather> // 此处必须为List,不能是单个Weather对象
)

data class Main(
    @SerializedName("temp") // 注意API返回字段为temp,需与模型字段映射
    val temperature: Double
)

data class Weather(
    val description: String,
    val icon: String
)

注意:要保证字段名与API返回完全一致,或通过@SerializedName做映射匹配。

3. 处理日志中的兼容性提示

你提供的日志里出现W/ple.weather_ap: Accessing hidden method Lsun/misc/Unsafe;-&gt;getInt(Ljava/lang/Object;J)I,这通常是Gson版本与Android系统的兼容性问题,可在build.gradle中添加以下配置解决:

android {
    compileOptions {
        coreLibraryDesugaringEnabled true
    }
}

dependencies {
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.0.4'
}

4. 其他排查点

  • 确认getClient()方法中的BaseUrl是否正确(OpenWeatherAPI的BaseUrl为https://api.openweathermap.org/data/2.5/)
  • 确认请求时是否携带了合法的API Key(OpenWeatherAPI要求在请求参数中添加appid=你的密钥)
  • 检查AndroidManifest.xml是否声明了网络权限:<uses-permission android:name="android.permission.INTERNET" />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:10:29