java验证码短信发送_java发送短信验证码

1.选择一个短信平台,因为之前项目用的是赛邮云通信(submail),所以在这里以此为例。

2.需要到平台上创建账号,先参阅api文档研究入参。

(1)需要用到应用Id和密钥进行身份鉴权,在应用集成-》应用页面进行创建

(2)创建短信模板,短信-》新建 页面可以创建新的短信模板

3.接口调用

用到的jar包:commons-logging.jar  gson.jar  httpclient.jar  httpcore.jar  json-simple.jar

HttpPost httpPost = new HttpPost();

CloseableHttpClient client = HttpClientBuilder.create().build();

httpPost.setURI(new URI("https://api.submail.cn/message/xsend.json"));

List params = new ArrayList();

params.add(new BasicNameValuePair("appid", "*****")); //(1)中创建的appid

params.add(new BasicNameValuePair("to", "***********")); //发送的手机号

params.add(new BasicNameValuePair("project", "****")); //(2)中创建的短信模板标识

params.add(new BasicNameValuePair("signature", "*****************")); //(1)中创建的密钥

Map vars = new HashMap<>();

vars.put("code","5555");

params.add(new BasicNameValuePair("vars", JSONObject.toJSONString(vars))); //模板中可设可变参数,这里为传参。 在模板中的设置为@var(code)

httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));

HttpResponse response = client.execute(httpPost);

String s = EntityUtils.toString(response.getEntity());

System.out.println(s);

4.一般短信验证码会有时间限制,即几分钟内有效。这里用到的是redis来存取验证码及控制时间。

话不多说,上源码!

@Resource

private RedisTemplate redisTemplate;

BoundValueOperations valueOps = redisTemplate.boundValueOps(phone);

String code = (String) valueOps.get();

//发送短信间隔时间1分钟,验证码有效时间2分钟

int timeout = 1;

int expireMinute = 2;

int codeLength = 6;

if (StringUtils.isNotEmpty(code)) {

Long expire = valueOps.getExpire();

if (expire >= (expireMinute - timeout) * 60) {

throw new ServiceException(StatusCode.ERROR_COMMON, "发送验证码间隔不能小于" + timeout + "分钟");

} else {

code = RandomStringUtils.getRandomNumberStr(codeLength); //此方法为创建一个随机六位数,即验证码。

valueOps.set(code);

valueOps.expire(expireMinute, TimeUnit.MINUTES);

}

} else {

code = RandomStringUtils.getRandomNumberStr(codeLength);

valueOps.set(code);

valueOps.expire(expireMinute, TimeUnit.MINUTES);

}

OK,到这里就搞定了!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值