[英]Kotlin RESTful calls using Retrofit
我正在尝试学习如何使用 Retrofit 从 Kotlin 进行 REST 调用。 我遵循了Loopcupcakes.com上的示例,该示例可以正常工作并将结果很好地写入 logcat。 这一切都很好,我(大体上)理解它在做什么。 我现在正在尝试调整它以使用我的 API,但是我的跑步前我可以走路的方法给我的实施带来了问题。
我的 API 工作正常,并在 postman 中返回结果
{
"APIResult": [
{
"id": 200,
"status_message": "Success",
"developer_message": "",
"user_message": "Success",
"suppliers": [
{
"supplier_name": "Supplier 1",
"tariff_name": "Variable 1",
"tariff_start_date": "2021-04-01"
},
{
"supplier_name": "Supplier 2",
"tariff_name": "Fixed",
"tariff_start_date": "2021-05-01"
}
]
}
]
}
Kotlin中的调用不返回错误,但是logcat显示D/TAG_: null
我有 gradle 和清单权利,因为原始代码正在工作。 这是我的代码:
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val service = Retrofit.Builder()
.baseUrl("https://api.domain.com/")
.addConverterFactory(MoshiConverterFactory.create())
.build()
.create(CurrentSupplier::class.java)
service.getSupplier().enqueue(object : Callback<SupplierResponse> {
override fun onFailure(call: Call<SupplierResponse>, t: Throwable) {
Log.d("TAG_", "An error happened!")
t.printStackTrace()
}
override fun onResponse(call: Call<SupplierResponse>, response: Response<SupplierResponse>) {
/* This will print the response of the network call to the Logcat */
Log.d("TAG_", response.body().toString())
}
})
}
}
data class SupplierResponse(val results: List<Supplier>)
data class Supplier(val id: Int)//, val tariff_name: String)
interface CurrentSupplier {
@GET("/supplier?key=xxx&ipaddress=1.1.1.1&operation=current")
fun getSupplier(): Call<SupplierResponse>
}
所以,我的问题是,如何配置接口和/或数据类以获取供应商名称和关税名称元素?
尝试删除接口CurrentSupplier
的getSupplier()
上的第一个“/”
如果您想了解有关 retrofit 调用的更多信息,您可以使用日志拦截器Logging with Retrofit 2
我认为 SupplierResponse 与 Call 的返回类型不匹配。 您可以用字符串替换 SupplierResponse 并记录响应。 如果不是 null,则必须更改 SupplierResponse。
您的BASE_URL
如下
https://api.domain.com/
现在来到你的接口调用,这是
@GET("/supplier?key=xxx&ipaddress=1.1.1.1&operation=current")
相信结局URL变成这样
https://api.domain.com//supplier?key=xxx&ipaddress=1.1.1.1&operation=current
我认为这不是正确的领域。 所以你可以摆脱额外的/
,你应该对go很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.