okHttp 更改请求的超时时间

以单例的形式使用 OKhttp,全局已经设置了超时时间

builder.connectTimeout(5, TimeUnit.SECONDS)
  .readTimeout(5, TimeUnit.SECONDS)
  .writeTimeout(5, TimeUnit.SECONDS)

某个接口(比如上传图片)需要不同的超时时间,怎么设置?

1、添加一个自定义注解

@Retention
@Target(allowedTargets = [AnnotationTarget.FUNCTION])
annotation class SpecificTimeout(val duration: Int, val unit: TimeUnit)

2、在方法上使用注解

@POST("/xxxx/xxxx/xxxx")
@SpecificTimeout(45, TimeUnit.SECONDS)
suspend fun payBOC(@Body payBOC: PayBOC): BaseBean

3、自定义拦截器

class TimeOutInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        //有些方法需要不一样的超时时间
        request.tag(Invocation::class.java)
            ?.method()
            ?.getAnnotation(SpecificTimeout::class.java)
            ?.let {
                return chain.withConnectTimeout(it.duration, it.unit)
                    .withReadTimeout(it.duration, it.unit)
                    .withWriteTimeout(it.duration, it.unit)
                    .proceed(request)
            } ?: kotlin.run {
            return chain.proceed(request)
        }
    }
}

4、加上拦截器

builder.addInterceptor(TimeOutInterceptor())
  .connectTimeout(5, TimeUnit.SECONDS)
  .readTimeout(5, TimeUnit.SECONDS)
  .writeTimeout(5, TimeUnit.SECONDS)

你可能感兴趣的:(okHttp 更改请求的超时时间)