我的GET请求在Android Studio中无法正常运行。我试图在邮递员中提出相同的请求,结果我总是得到带有正确正文的响应代码200。但是,使用Retrofit时,当响应主体为空(没有数据)时,我会收到onResponse(200代码),而当响应主体不为空(有一些保留)时,我会得到onFailure。
编辑:我刚刚在日志中注意到这样的错误:Expected BEGIN_OBJECT but was STRING at line 1 column 22 path $[0].reservationDate
EDIT2:JSON响应
[
{
"reservationDate": "2019-10-30",
"id": "4"
}
]
API服务:
@Headers("Authorization: Bearer ...")
@GET("reservations")
fun getSchedule(@Query("id") id: Int,
@Query("reservationDate") reservationDate: LocalDate
): Call<List<ScheduleModel>>
companion object {
fun create(): ScheduleService{
var retrofit = Retrofit.Builder()
.baseUrl("myUrl")
.addConverterFactory(GsonConverterFactory.create())
.build()
return retrofit.create(ScheduleService::class.java)
}
}
}
data class ScheduleModel(
val id: Int,
val reservationDate: LocalDate
)
fun getReservations() {
var service = ScheduleService.create()
var localdate = LocalDate.of(2019,10,30)
var call = service.getSchedule(4, localdate)
call.enqueue(object : Callback<List<ScheduleModel>> {
override fun onResponse(call: Call<List<ScheduleModel>>, response: Response<List<ScheduleModel>>) {
if (response.code() == 200) {
Toast.makeText(applicationContext, "It's ok", Toast.LENGTH_SHORT).show()
}
}
override fun onFailure(call: Call<List<ScheduleModel>>, t: Throwable) {
Toast.makeText(applicationContext, "Failure", Toast.LENGTH_SHORT).show()
}
})
}
答案 0 :(得分:2)
您的id
和reservationDate
的响应是一个String
,但是您尝试将其解析为Int
和LocalDate
。更改类型,它将起作用。