Retrofit集成天气API时应用崩溃问题求助(含DI配置)
Retrofit集成Weather API崩溃问题修复方案
核心问题分析
你的代码主要存在4个关键错误,导致应用崩溃:
BASE_URL配置完全错误,包含了完整查询参数和多余斜杠,违反Retrofit的baseUrl规范- 重复创建Retrofit实例(依赖注入+接口伴生对象),导致初始化冲突
- API接口端点和返回类型不匹配,用错了WeatherAPI的接口路径
- 拦截器配置冗余且无效
修正后的代码
1. 常量配置文件
package const const val BASE_URL = "https://api.weatherapi.com/v1/" const val API_KEY = "a9f9d57b6e064f16b28141346231001" const val WEATHER_DAYS = 10
2. WeatherServiceAPI接口
interface WeatherServiceAPI { // 获取指定天数的天气预报 @GET("forecast.json") suspend fun getWeatherForecast( @Query("q") location: String = "London", @Query("days") days: Int, @Query("aqi") aqi: String = "no", @Query("alerts") alerts: String = "no" ): WeatherResponse // 根据经纬度搜索城市(必须同时传lat和lon) @GET("search.json") suspend fun searchCityByCoord( @Query("lat") lat: String, @Query("lon") lon: String ): List<WeatherLocationDTO> // 根据城市名搜索 @GET("search.json") suspend fun searchCityByName(@Query("q") cityName: String): List<WeatherLocationDTO> }
3. 依赖注入配置
@Provides @Singleton fun provideRepository(api: WeatherServiceAPI): ForecastRepository { return ForecastRepositoryImpl(api) } @Provides @Singleton fun provideWeatherApiService(retrofit: Retrofit): WeatherServiceAPI { return retrofit.create(WeatherServiceAPI::class.java) } @Provides @Singleton fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit { return Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .baseUrl(BASE_URL) .client(okHttpClient) .build() } @Provides @Singleton fun provideOkHttpClient(): OkHttpClient { // 自动给所有请求添加API_KEY参数 val requestInterceptor = Interceptor { chain -> val newUrl = chain.request().url.newBuilder() .addQueryParameter("key", API_KEY) .build() val newRequest = chain.request() .newBuilder() .url(newUrl) .build() chain.proceed(newRequest) } return OkHttpClient.Builder() .addInterceptor(requestInterceptor) // 如果需要网络状态拦截器,在这里添加 // .addInterceptor(connectivityInterceptor) .build() }
关键修复点说明
- BASE_URL规范:只保留基础域名和路径,必须以
/结尾,不能包含任何查询参数 - 移除重复实例:删除接口伴生对象里的Retrofit创建逻辑,完全依赖DI管理实例,避免冲突
- 接口端点修正:搜索城市要用
search.json而非forecast.json,这是WeatherAPI的官方接口划分 - 参数完整性:经纬度搜索必须同时传
lat和lon,否则接口无法返回有效结果 - 拦截器优化:统一用拦截器自动注入API_KEY,避免每个接口都手动写参数,移除无用的空拦截器
内容的提问来源于stack exchange,提问作者user20498005
相关产品推荐
相关产品推荐

