首页 > 编程语言 > 详细

java发送短信验证码

时间:2019-04-19 15:57:27      阅读:161      评论:0      收藏:0      [点我收藏+]

本文作者:回头不是岸


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<NameValuePair> params = new ArrayList<NameValuePair>();
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<String,String> 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,到这里就搞定了!

 

java发送短信验证码

原文:https://www.cnblogs.com/submail/p/10736085.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!