改造:java.lang.IllegalStateException:关闭

Sid*_*mit 15 android retrofit2

我使用了两种拦截器,一种是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'
Run Code Online (Sandbox Code Playgroud)

下面是代码

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()
    }
Run Code Online (Sandbox Code Playgroud)

当我尝试在名为 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)               
Run Code Online (Sandbox Code Playgroud)

我的 RulesResourcesServices 课程在这里

调试后我发现当下面的函数被调用时,我得到了一个异常

@GET("users/me/configfile")
    fun getConfigFile(@Query("type") type: String): Call<ResponseBody>
Run Code Online (Sandbox Code Playgroud)

我收到以下错误

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)
Run Code Online (Sandbox Code Playgroud)

下面是屏幕截图,您可以看到,我正在获取文件输出,但不知道为什么会抛出异常。

在此处输入图片说明

检查 Retrofit 的 Utils 类

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);
  }
Run Code Online (Sandbox Code Playgroud)

更新

同样的事情用 enqueue 方法工作正常。

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

override fun onResponse(call: Call<ResponseBody?>, response: retrofit2.Response<ResponseBody?>) { 
 }
})
Run Code Online (Sandbox Code Playgroud)

我在改造团队中发布了同样的问题,让我们看看。

https://github.com/square/retrofit/issues/3336

Sid*_*mit 31

感谢 JakeWharton ( https://github.com/square/retrofit/issues/3336 ),我可以获得解决方案。实际上在我的自定义拦截器中,我正在通过以下代码读取响应

Response.body().string()
Run Code Online (Sandbox Code Playgroud)

我这样做是因为上面的代码帮助我找出是否有任何错误而不是它是哪种错误......

如果是 AUTH_ERROR,我必须生成新令牌并将其附加到请求标头。

根据改造文档,如果我们调用以下任何方法,则响应将被关闭,这意味着它不能被正常的改造内部使用。

Response.close()
Response.body().close()
Response.body().source().close()
Response.body().charStream().close()
Response.body().byteStream().close()
Response.body().bytes()
Response.body().string()
Run Code Online (Sandbox Code Playgroud)

所以要读取数据,我将使用

 response.peekBody(2048).string()
Run Code Online (Sandbox Code Playgroud)

代替

 response.body().string(), 
Run Code Online (Sandbox Code Playgroud)

所以它不会关闭响应。

下面是最终代码

 val response = chain.proceed(request)
            val body = response.peekBody(2048).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
Run Code Online (Sandbox Code Playgroud)

  • 使用这种方法要小心。如果您的响应长度超过 2048 字节,Retrofit 将抛出“java.io.EOFException” (2认同)
  • @SamanSattari JakeWharton 提到使用 `.peekBody(Long.MAX_VALUE)` [在此 github 评论中](https://github.com/square/okhttp/issues/2869#issuecomment-248112784) (2认同)

Moh*_*had 6

扩展@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();
Run Code Online (Sandbox Code Playgroud)

  • 对于 Kotlin,ResponseBody.create 已弃用。相反,使用:responseBodyString.toResponseBody(response.body.contentType()) (2认同)