这是拦截器代码,我不知道在哪里调用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()
}
}
}
1条答案
按热度按时间hxzsmxv21#
您应该在调用
chain.proceed(request)
方法之前关闭该方法,这样您的代码将如下所示有关详细信息,您可以查看此答案https://stackoverflow.com/a/31733634/5696047
我不知道你为什么要添加
Thread.sleep(1500)
,但我认为这不是必需的