提问者:小点点

Retrofit 2和kotlin:未反序列化问题:IllegelArgumentException:关闭


嗨,我是新来的,我正在使用

implementation 'com.squareup.retrofit2:retrofit:2.6.1'
// JSON Parsing
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'

我正在对login进行API调用。调用成功(我可以在添加的拦截器中看到200响应),但我仍然使用java. lang.IllegalStateException:关闭作为throwable在改造中获得onFailure回调。我在Retrofit类中添加了一些断点,它似乎是在解析我的响应时出现的。我也使用静态编程语言

这是我的数据类:

data class LoginResponse(
    @SerializedName("payload") @Expose val payload: Payload,
    @SerializedName("status") @Expose val status: Int
)
data class Payload(
    @SerializedName("access_token") @Expose val access_token: String?,
    @SerializedName("expires_at") @Expose val expires_at: String?,
    @SerializedName("name") @Expose val name: String?,
    @SerializedName("org_name") @Expose val org_name: String?,
    @SerializedName("request_at") @Expose val request_at: String,
    @SerializedName("status_message") @Expose val status_message: String
)

以下是我创建改造实例的方式:

private val okHttpClient = OkHttpClient.Builder().addInterceptor(Interceptor {
    Log.w("Retrofit@Request", it.request().toString())
    val requestBuilder = it.request().newBuilder()
    requestBuilder.header("Content-Type", "application/json")
    val response = it.proceed(it.request())
    Log.w("Retrofit@Response", response.body()!!.string())  //correct 200 response with json is printed out here
    return@Interceptor response
}).build()

val retrofitInstance: Retrofit
    get() {
        if (retrofit == null) {
            retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        }
        return retrofit!!
    }

以下是我打电话的方式:

loginService.login(logindata).enqueue(object : Callback<LoginResponse> {
                override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
                    Log.d(TAG, "Login failure "+t) //this is getting invoked with java.lang.IllegalStateException: closed
                }

                override fun onResponse(
                    call: Call<LoginResponse>,
                    response: Response<LoginResponse>
                ) {
                    onLoginState.value = true
                }
            })

我花了很多时间试图弄清楚发生了什么,找不到我在这里做错了什么。我还尝试用Moshi替换GSON,这给了我同样的错误。请帮我解决这个问题。

提前感谢。


共1个答案

匿名用户

我不知道这是否有帮助,但试着阅读这篇文章

// Don't try to use response.body.string() directly. Just using like below:
ResponseBody responseBody = response.body();
String content = responseBody.string();
// Do something with "content" variable

原因:body的string()在内存中存储为变量content,所以我们不需要关心状态是否关闭。