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