TL;
我正在使用用户名和密码参数进行post-call。实际调用正在工作,HTTP响应成功,但返回以下错误:
误差
com.google.gson.JsonIOException: Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter for this type. Interface name: retrofit2.Call
W/System.err: at com.google.gson.internal.ConstructorConstructor$3.construct(ConstructorConstructor.java:136)
W/System.err: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$FieldReflectionAdapter.createAccumulator(ReflectiveTypeAdapterFactory.java:427)
W/System.err: at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:383)
W/System.err: at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:40)
W/System.err: at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:27)
W/System.err: at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:243)
W/System.err: at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:153)
W/System.err: at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
服务@FormUrlEncoded
@POST("login")
suspend fun authenticateUser(@Field("email") email: String, @Field("password") password: String): Call<LoginResponse>
TL;用Response
代替Call
Response
代替Call
详细信息你在这里混合了悬挂风格和基于Call
的Retrofit用法:
- 如果您想从使用挂起方法中获益(提示:您确实这样做),
authenticateUser
的返回类型应该是Response<LoginResponse>
而不是Call<LoginResponse>
:
@FormUrlEncoded
@POST("login")
suspend fun authenticateUser(@Field("email") email: String, @Field("password") password: String): Response<LoginResponse>
- 如果你想使用Retrofit的
Call
,你应该使它不可挂起,并使用Call::enqueue
(异步调用)或Call::execute
(同步调用):
@FormUrlEncoded
@POST("login")
fun authenticateUser(@Field("email") email: String, @Field("password") password: String): Call<LoginResponse>
...
// Somewhere
//This
val loginResponse = authenticateUser("email", "password).execute() // throws IOException upon problem talking to the server
// Or this
authenticateUser("email", "password).enqueue(object:Callback<LoginResponse>{
override fun onResponse(call: Call<LoginResponse>, response: Response<LoginResponse>) {
// It worked!
}
override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
// Something went wrong
}
})
看- Retrofit 2.6.0版本变更日志(引入
suspend
支持) - 改造的网页
- 改造的javadoc