安卓 okhttp 拦截重复请求


okhttp拦截重复请求,如果请求存在则取消最新请求

/**
 * @author zhangwei on 2020/12/23.
 * 用于拦截重复请求
 */
class HttpInterceptor : Interceptor {
    private val requestMap = LinkedHashMap<String, Long>()//实现拦截重复请求

    override fun intercept(chain: Interceptor.Chain): Response {
        val key = chain.request().url().toString()//请求url
        val time = System.currentTimeMillis()//请求时间
        try {
            if (requestMap.size > 0 && requestMap.containsKey(key)) {
                chain.call().cancel()
                throw IOException("cancel")
            }
            requestMap[key] = time
            val builder = chain.request().newBuilder()
            builder.addHeader("header", jsonObject.toString())
            return chain.proceed(builder.build())
        } catch (e: IOException) {
            throw e
        } finally {
            if (requestMap.containsKey(key) && requestMap.containsValue(time)) {//请求任务完成删除map中的数据
                requestMap.remove(key)
            }
        }
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM