Android: How to use URL parameters with Retrofit in Kotlin.
Let’s say you have an Android app and you want to download a JSONArray from a URL that requires parameters using Retrofit in Kotlin.
How would you go about making this happen?
Well first, here’s an example of a possible URL: https://someurl.com/getWebArray?id=201
The parameter “id” is dynamically inputted depending on the request you need.
How do you make that happen in Retrofit.
You simply need to replace the “?id=201” of the URL and set it up as @Query parameter, as such: @Query(“id”) id: Int.
Here’s an example of what you interface would look like.
interface WebService {
@GET("getWebArray")
fun getTripCoord(
@Header("Authorization") token: String,
@Query("id") id: Int
): Deferred<JSONArray>
companion object{
operator fun invoke(
connectivityInterceptor: ConnectivityInterceptor
):WebService{
val okHttpClient = OkHttpClient.Builder().addInterceptor(connectivityInterceptor).build()
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl("https://someurl.com/")
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(TripsService::class.java)
}
}
}