0

这是我的改造界面和创建代码:

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仍然附加到 my 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/"
}
4

1 回答 1

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"

这里有一篇文章讨论了动态URL在不同场景下是如何解析的,供进一步参考。

于 2018-06-20T10:00:03.820 回答