【发布时间】:2019-10-26 16:03:06
【问题描述】:
我正在尝试通过 Retrofit 2 发送 GET 请求。
但是,请求没有做任何事情..
API 服务
package com.example.brews.network
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import kotlinx.coroutines.Deferred
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
/*
This is the sandbox base url (way less data than production environment)
When deploying app -> use production base url
*/
private const val BASE_URL = "https://sandbox-api.brewerydb.com/v2/"
/**
* Build the Moshi object that Retrofit will be using, making sure to add the Kotlin adapter for
* full Kotlin compatibility.
*/
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
/**
* Use the Retrofit builder to build a retrofit object using a Moshi converter with our Moshi
* object.
*/
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.baseUrl(BASE_URL)
.build()
/**
* A public interface that exposes the [getProperties] method
*/
interface BreweryApiService {
/**
* Returns a Coroutine [Deferred] [List] of [BeerProperty] which can be fetched with await() if
* in a Coroutine scope.
* The @GET annotation indicates that the "beers" endpoint will be requested with the GET
* HTTP method
*/
@GET("beers/")
fun getProperties(@Query("?key") key: String):
// The Coroutine Call Adapter allows us to return a Deferred, a Job with a result
Deferred<List<BeerProperty>>
}
/**
* A public Api object that exposes the lazy-initialized Retrofit service
*/
object BreweryApi {
val retrofitService: BreweryApiService by lazy { retrofit.create(BreweryApiService::class.java) }
}
数据类
package com.example.brews.network
data class BeerProperty(
val id: Int,
val name: String
)
填满我的列表的方法
private fun getBeersProperties() {
coroutineScope.launch {
var getPropertiesDeferred =
BreweryApi.retrofitService.getProperties("13e9caaf80adac04dce90ef55600d898")
try {
_status.value = BreweryApiStatus.LOADING
val listResult = getPropertiesDeferred.await()
_status.value = BreweryApiStatus.DONE
_properties.value = listResult
} catch (e: Exception) {
_status.value = BreweryApiStatus.ERROR
_properties.value = ArrayList()
}
}
}
链接检索到的 JSON
{
“当前页面”:1,
“页数”:23,
“总结果”:1109,
“数据”: [
{
“id”:“c4f2KE”,
"name": "'Murican Pilsner",
"nameDisplay": "'Murican Pilsner",
“abv”:“5.5”,
"glasswareId": 4,
“styleId”:98,
"isOrganic": "N",
“已退休”:“N”
}
]
}
我需要检索的是“数据”中的“ID”和“名称”。但是,这是一个数组,我不知道如何通过改造来提取它..
【问题讨论】:
标签: java android kotlin retrofit retrofit2