安卓 okhttp 攔截重複請求
阿新 • • 發佈:2021-07-02
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) } } }}