Android 应用经常通过网络与 APIs 通信。标准方法使用 Retrofit(REST 客户端)和 OkHttp 等库,配合 coroutines 实现异步,以及 JSON 解析 — 在主线程外干净正确地处理网络调用。
Retrofit — 标准 REST 客户端
{
: User
: User
}
api = Retrofit.Builder()
.baseUrl()
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiService::.java)
viewModelScope.launch {
user = api.getUser()
}
