安卓 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)
            }
        }
    }
}

 

posted @ 2021-07-02 15:19  别人眼中的过客  阅读(1186)  评论(0编辑  收藏  举报