java.lang.IllegalStateException: cannot make a new request because the previous response is still open: please call response.close()

enter image description hereThis is the interceptor code i cant figure out where to call the response.close() on the logCat it states that the error appears on the "response = chain.proceed(request). Where do i place the response.close() call or do i use 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()
    }

}

}

Upvotes: 1

Views: 5229

Answers (2)

Sahil Kumar
Sahil Kumar

Reputation: 1

I made file Name to unique for every download

For Example : Add Date and Time at the end is an option to make every file unique (It works for me)

Upvotes: 0

jayesh gurudayalani
jayesh gurudayalani

Reputation: 1701

You should close just before you call chain.proceed(request) method so your code will be like this

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

        }

For more information , you can see this answer https://stackoverflow.com/a/31733634/5696047

I am not aware why you have added Thread.sleep(1500) but I don't think it is required

Upvotes: 3

Related Questions