android 修改:java.lang.非法状态异常:封闭的

vltsax25  于 2023-02-02  发布在  Android
关注(0)|答案(3)|浏览(188)

我正在使用两种拦截器,一种是HttpLoggingInterceptor,另一种是我的自定义AuthorizationInterceptor
我正在使用下面更新的翻新版本库,

def retrofit_version = "2.7.2"
implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
implementation "com.squareup.retrofit2:converter-gson:$retrofit_version"
implementation 'com.squareup.okhttp3:logging-interceptor:4.4.0'
implementation 'com.squareup.okhttp3:okhttp:4.4.0'

下面是代码

private fun makeOkHttpClient(): OkHttpClient {
        val logger = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
        return OkHttpClient.Builder()
            .addInterceptor(AuthorizationInterceptor(context)) <---- To put Authorization Barrier
            .addInterceptor(logger) <---- To log Http request and response
            .followRedirects(false)
            .connectTimeout(50, TimeUnit.SECONDS)
            .readTimeout(50, TimeUnit.SECONDS)
            .writeTimeout(50, TimeUnit.SECONDS)
            .build()
    }

当我试图执行下面的代码时,在名为SynchronizationManager.kt的文件中,它给我一个错误。

var rulesResourcesServices = RetrofitInstance(context).buildService(RulesResourcesServices::class.java)
val response = rulesResourcesServices.getConfigFile(file).execute() <---In this line I am getting an exception... (which is at SynchronizationManager.kt:185)

我的RulesResourcesServices类在这里
调试后我发现当下面的函数被调用时,当时我得到一个异常

@GET("users/me/configfile")
    fun getConfigFile(@Query("type") type: String): Call<ResponseBody>

我收到以下错误

java.lang.IllegalStateException: closed
at okio.RealBufferedSource.read(RealBufferedSource.kt:184)
at okio.ForwardingSource.read(ForwardingSource.kt:29)
at retrofit2.OkHttpCall$ExceptionCatchingResponseBody$1.read(OkHttpCall.java:288)
at okio.RealBufferedSource.readAll(RealBufferedSource.kt:293)
at retrofit2.Utils.buffer(Utils.java:316)<------- ANDROID IS HIGH-LIGHTING
at retrofit2.BuiltInConverters$BufferingResponseBodyConverter.convert(BuiltInConverters.java:103)
at retrofit2.BuiltInConverters$BufferingResponseBodyConverter.convert(BuiltInConverters.java:96)
at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:225)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:188)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall.execute(DefaultCallAdapterFactory.java:97)
at android.onetap.SynchronizationManager.downloadFile(SynchronizationManager.kt:185)
at android.base.repository.LoginRepository.downloadConfigFilesAndLocalLogin(LoginRepository.kt:349)
at android.base.repository.LoginRepository.access$downloadConfigFilesAndLocalLogin(LoginRepository.kt:48)
at android.base.repository.LoginRepository$loginTask$2.onSRPLoginComplete(LoginRepository.kt:210)
at android.base.repository.LoginRepository$performSyncLogin$srpLogin$1$1.onSRPLogin(LoginRepository.kt:478)
at android.srp.SRPManager$SRPLoginOperation$execute$1.invokeSuspend(SRPManager.kt:323)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:56)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:561)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:727)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:667)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:655)

下面是屏幕截图,你可以看到,我得到文件的输出,但不知道为什么它抛出一个异常。

已检查Retrofit的实用程序类
https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit2/Utils.java

static ResponseBody buffer(final ResponseBody body) throws IOException {
    Buffer buffer = new Buffer();
    body.source().readAll(buffer); <-This line throws an error.
    return ResponseBody.create(body.contentType(), body.contentLength(), buffer);
  }

更新

同样的事情也适用于enqueue方法。

response.enqueue(object : Callback<ResponseBody?> {

override fun onResponse(call: Call<ResponseBody?>, response: retrofit2.Response<ResponseBody?>) { 
 }
})

我已经发布了相同的问题与改造团队,让我们看看。
https://github.com/square/retrofit/issues/3336

4xrmg8kj

4xrmg8kj1#

多亏了JakeWharton(https://github.com/square/retrofit/issues/3336),我才能得到解决方案。实际上,在我的自定义拦截器中,我通过以下代码阅读响应

Response.body().string()

我这样做是因为上面的代码是帮助我找出,如果有任何错误比什么样的错误是...。
如果是AUTH_ERROR,我必须生成新令牌并将其附加到请求头中。
根据retrofit document,如果我们调用以下任何方法,则响应将被关闭,这意味着它不能被正常的Retrofit内部使用。

Response.close()
Response.body().close()
Response.body().source().close()
Response.body().charStream().close()
Response.body().byteStream().close()
Response.body().bytes()
Response.body().string()

为了读取数据,我将使用

response.peekBody(2048).string()

代替

response.body().string(),

因此不会关闭响应。
下面是最终代码

val response = chain.proceed(request)
            val body = response.peekBody(Long.MAX_VALUE).string()//<---- Change
            try {
                if (response.isSuccessful) {
                    if (body.contains("status")) {
                        val jsonObject = JSONObject(body)
                        val status = jsonObject.optInt("status")
                        Timber.d("Status = $status")
                        if (status != null && status == 0) {
                            val errorCode = jsonObject.getJSONObject("data").optString("error_code")
                            if (errorCode != null) {
                                addRefreshTokenToRequest(request)
                                return chain.proceed(request)
                            }
                        }
                    } else {
                        Timber.d("Body is not containing status, might be not valid GSON")
                    }
                }
                Timber.d("End")
                
            } catch (e: Exception) {
                e.printStackTrace()
                Timber.d("Error")
            }
            return response
xpszyzbs

xpszyzbs2#

延伸@Siddhpura Amit的回答:如果你不知道要传递给peak方法的字节数,那么你仍然可以使用所有的方法,但是只需要创建一个新的Response对象。
拦截器内部:

okhttp3.Response response = chain.proceed(request);
String responseBodyString = response.body().string();

//Do whatever you want with the above string

ResponseBody body = ResponseBody.create(response.body().contentType(), responseBodyString);
return response.newBuilder().body(body).build();
oxiaedzo

oxiaedzo3#

可能您在AuthorizationInterceptor中关闭了响应,如下所示

override fun intercept(chain: Interceptor.Chain): Response {
   ...
   val response = chain.proceed(builder.build())
   response.close()
   ...
}

相关问题