Retrofit简单使用
约 90 字小于 1 分钟
kotlin
2023-08-13
ServiceCreator.kt
object ServiceCreator {
private const val BASE_URL = "https://api.caiyunapp.com/"
private val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
fun <T> create(serviceClass: Class<T>): T = retrofit.create(serviceClass)
inline fun <reified T> create(): T = create(T::class.java)
}
Service.kt
interface PlaceService {
@GET("v2/place?lang=zh_CN")
fun searchPlaces(@Query("query") query: String): Call<PlaceResponse>
}
Network.kt
object SunnyWeatherNetwork {
private val placeService = ServiceCreator.create<PlaceService>()
suspend fun searchPlaces(query: String) = placeService.searchPlaces(query).await()
}