Java手机验证码

本文介绍了一种使用OkHttp发起请求以发送手机验证码的方法,并利用Caffeine实现了验证码和请求冷却时间的本地缓存。文章详细展示了如何构建OkHttpClient实例、设置请求头以及通过第三方短信服务发送验证码。
摘要由CSDN通过智能技术生成
 private final OkHttpClient client = new OkHttpClient.Builder().connectTimeout(3, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).retryOnConnectionFailure(false).build();
    private final String header = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1";

    private final Cache<String, Date> locker = Caffeine.newBuilder().expireAfterWrite(120, TimeUnit.SECONDS).initialCapacity(10000).maximumSize(100000).build();
    private final Cache<String, String> vcode = Caffeine.newBuilder().expireAfterWrite(600, TimeUnit.SECONDS).initialCapacity(10000).maximumSize(100000).build();




 /**
     * 获取手机验证码
     *
     * @param loginName
     * @return
     */
    @ApiIgnore
    @RequestMapping(path = {"user-verification"}, method = {RequestMethod.POST})
    public AjaxReturn getVerification(String loginName) {
        Date ifPresent = locker.getIfPresent(loginName);
        if (ifPresent != null) {
            if (new Date().getTime() - ifPresent.getTime() < 60000) {
                return new AjaxReturn(500, "验证码已发送,请勿重复发送!", null);
            }
        }
        Request request;
        Response response = null;
        String code;
        try {
            code = StringUtils.randomStr(6);
            String context = "【平台名称】请输入验证码" + code + "完成验证。";
            StringBuffer sb = new StringBuffer();
            sb.append("http://www.bjhx106.com/sms.aspx");
            sb.append("?action=send");
            sb.append("&userid=" + "716");
            sb.append("&account=" + "帐号");
            sb.append("&password=" + "密码");
            sb.append("&mobile=" + 手机号);
            sb.append("&content=" + context);
            request = new Request.Builder().url(sb.toString()).addHeader("User-Agent", header).build();
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                locker.put(loginName, new Date());
                vcode.put(loginName, code);
            }
        } catch (Exception e) {
            return new AjaxReturn(500, "获取验证码失败,请重试!", null);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return new AjaxReturn(200, null, null);
    }
//注册成功后
locker.invalidate(memUserInfo.getLoginName());
        vcode.invalidate(memUserInfo.getLoginName());

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值