android java.lang.IllegalStateException:无法发出新请求,因为先前的响应仍处于打开状态:请调用response.close()

hjzp0vay  于 2023-05-21  发布在  Android
关注(0)|答案(1)|浏览(152)


这是拦截器代码,我不知道在哪里调用response.close()在logCat上它指出错误出现在“response = chain.proceed(request)”上。我应该在哪里放置response.close()调用,还是使用closeQuietly()
class AppInterceptor:Interceptor {

override fun intercept(chain: Interceptor.Chain): Response {
    var request = chain.request()

      try{
          var response = chain.proceed(request)
          var tryCount = 0
          val maxTries = 5

        while (!response.isSuccessful && tryCount < maxTries){
            tryCount++
            Thread.sleep(1500)
            request = request.newBuilder().build()
            response = chain.proceed(request)

        }
        return response

      }catch (e: Exception){
        e.printStackTrace()
        val message: String

        when (e){
            is SocketTimeoutException ->{
                message = Constants.SOCKET_TIMEOUT
            }

            is UnknownHostException ->{
                message = Constants.UNKNOWN_HOST
            }

            is ConnectionShutdownException ->{
                message = Constants.CONNECTION_SHUTDOWN
            }

            is IOException ->{
                message = Constants.IO_EXCEPTION_MESSAGE
            }

            is IllegalStateException ->{
                message = "${e.message}"
            }
            else ->{
                message = "${e.message}"
            }
        }
        return Response.Builder()
            .request(request)
            .protocol(Protocol.HTTP_1_1)
            .code(999)
            .message(message)
            .body("{${e}".toResponseBody(null))
            .build()
    }

}

}

hxzsmxv2

hxzsmxv21#

您应该在调用chain.proceed(request)方法之前关闭该方法,这样您的代码将如下所示

while (!response.isSuccessful && tryCount < maxTries){
            tryCount++
            request = request.newBuilder().build()
            response.close() // here you need to add
            response = chain.proceed(request)

        }

有关详细信息,您可以查看此答案https://stackoverflow.com/a/31733634/5696047
我不知道你为什么要添加Thread.sleep(1500),但我认为这不是必需的

相关问题