这是我的改造界面和创建代码:
interface SSApi {
companion object {
private fun create(): SSApi {
val httpClient = OkHttpClient().newBuilder()
val networkInterceptor = Interceptor { chain ->
val request = chain.request()?.newBuilder()?.addHeader("api-key", SSConstants.API_KEY)?.build()
chain.proceed(request!!)
}
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
httpClient.addNetworkInterceptor(networkInterceptor).addInterceptor(loggingInterceptor)
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(SSConstants.BASE_URL)
.client(httpClient.build())
.build()
return retrofit.create(SSApi::class.java)
}
val api by lazy {
SSApi.create()
}
var disposable: Disposable? = null
}
@GET
fun getWeatherInfo(@Url url: String): Observable<OpenWeatherMapInfo>
}
这是我使用disposable
的方式:
private fun getWeather() {
disposable = api
.getWeatherInfo(SSConstants.OPEN_WEATHER_MAP_API_ENDPOINT)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ results -> Log.i("Dale", results.toString())},
{ error -> Log.i("Dale", error.message)}
)
}
执行请求时,我可以看到我的OPEN_WEATHER_MAP_API_ENDPOINT
仍附加到我的baseUrl
上。
这是我的常量类供参考:
object SSConstants {
const val OPEN_WEATHER_MAP_API_ENDPOINT = "api.openweathermap.org/data/2.5/weather?q=Catbalogan,PH&units=metric"
const val BASE_URL = "https://api.xxx.xxx/"
}
答案 0 :(得分:1)
您的问题是,您没有在动态调用中提供完整的URL,这就是Retrofit试图相对于基本URL进行调用的原因。只需将https://
添加到动态URL:
const val OPEN_WEATHER_MAP_API_ENDPOINT = "https://api.openweathermap.org/data/2.5/weather?q=Catbalogan,PH&units=metric"
Here是一篇文章,讨论如何在不同情况下解析动态URL,以供进一步参考。