Search code examples
androidkotlinretrofit2rx-androidrx-kotlin

Retrofit Dynamic URL still appends to the Base URL


Here is my Retrofit Interface and creation code:

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>
}

And here is how I use the 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)}
            )
    }

When I execute the request, I can see that it my OPEN_WEATHER_MAP_API_ENDPOINT still appends to my baseUrl.

Here is my Constants class for reference:

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/"
}

Solution

  • Your issue is that you didn't provide the full URL in the dynamic call, and that's why Retrofit is trying to make the call relative to the base url still. Just add https:// to the dynamic URL:

    const val OPEN_WEATHER_MAP_API_ENDPOINT = "https://api.openweathermap.org/data/2.5/weather?q=Catbalogan,PH&units=metric"
    

    Here is an article discussing how the dynamic URL is resolved in different scenarios, for further reference.