JJD*_*JJD 8 kotlin retrofit retrofit2
给定以下Retrofit接口:
@GET("offices")
fun getOffices(@Query("uid") uid: String,
@Query("lat") latitude: Double,
@Query("lon") longitude: Double
): Call<List<Office>>
Run Code Online (Sandbox Code Playgroud)
如何用更用户友好的GeoLocation
类型替换位置参数...
data class GeoLocation(
val latitude: Double,
val longitude: Double
)
Run Code Online (Sandbox Code Playgroud)
...在请求时自动转换为lat
和lon
,例如:
@GET("offices")
fun getOffices(@Query("uid") uid: String,
@Query("location") location: GeoLocation
): Call<List<Office>>
Run Code Online (Sandbox Code Playgroud)
这是改造设置:
fun createRetrofit(baseUrl: String,
okHttpClient: OkHttpClient): Retrofit {
val moshi = Moshi.Builder()
.build()
return Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.client(okHttpClient)
.build()
}
Run Code Online (Sandbox Code Playgroud)
如果您关心用户友好的访问,您可以创建一个包装函数。这样您就不必弄乱您的 Retrofit 配置
fun getOffices(uid: String, location: GeoLocation): Call<List<Office>> {
return getOfficesIf(uid, location.lat, location.lon)
}
@GET("offices")
fun getOfficesIf(@Query("uid") uid: String,
@Query("lat") latitude: Double,
@Query("lon") longitude: Double
): Call<List<Office>>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5667 次 |
最近记录: |