简单防重复提交的方法

xiaoxiao2021-02-28  132

之前App做的防重复都是限制点击时间,短了就直接不处理;但是遇到网络不好的情况,请求长时间没返回,限制的点击时间还是会不够长,出现重复提交;

在请求工具类里写个list保存当前请求未返回的参数和Url的Md5,遇到相同的Md5即返回重复请求字串,处理时判断不处理即可;

private List<String> callCache = Collections.synchronizedList(new ArrayList<String>());/* * 提交参数方法 */ public String postUnprocess(String url, Map<String, String> parmas, Object tag, int msgId) { parmas.put("token", UserHelper.getToken()); String result = null; FormBody.Builder builder = new FormBody.Builder(); for (Entry<String, String> entry : parmas.entrySet()) { String key = entry.getKey().toString(); String value = entry.getValue().toString(); builder.add(key, value); } RequestBody body = builder.build(); Request request = new Request.Builder().url(url).tag(tag).post(body).build(); String chche_key = Md5.getMd5(url, parmas); if (callCache.contains(chche_key)) { LogUtils.d("douplicate"); return RsMsgBean.RsMsg_DupliCom; } callCache.add(chche_key); Call call = BaseApplication.getOkHttpClient().newCall(request); Response response = null; try { response = call.execute(); } catch (IOException e) { } callCache.remove(chche_key); if (response != null) { if (response.isSuccessful()) { try { result = response.body().string(); } catch (IOException e) { } } } LogUtils.logLongD(url + ":" + result); return result; } 要是请求带token,且token易变不要将token叠加取Md5,判断有可能会出错/** * 获取请求Url的Md5摘要 */ public static String getMd5(String url, Map<String, String> parmas) { StringBuilder sb = new StringBuilder(url); if (parmas != null) { for (Map.Entry<String, String> entry : parmas.entrySet()) { String key = entry.getKey().toString(); String value = entry.getValue().toString(); if (key != "token") sb.append("&" + key + "=" + value); } } return Md5.encodeByMd5(sb.toString()); } RsMsgBean.RsMsg_DupliCom 是个字串,处理的时候忽略掉这种情况就可以了 Object tag, int msgId 可以去掉

转载请注明原文地址: https://www.6miu.com/read-24252.html

最新回复(0)