一,注册对应的账户名和密码(密钥)在短信平台获取对应账号和密钥
二,编写对应的工具类
需要下载httpclient jar包
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
工具类
package com.meishi.mall.portal.util;
/**
* 短信 工具类
* @author chenxi
*
*/
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class HttpClientUtil {
//平台对应的请求地址
private static String Url = "http://api.uoleem.com.cn/sms/httpBatchSend";
public void getPost(String mobile, String content) {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(Url);
client.getParams().setContentCharset("UTF-8");
method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
NameValuePair[] data = {//提交短信
new NameValuePair("username", "用户名"),
new NameValuePair("pwd", "平台获取的密钥"),
new NameValuePair("mobile", 手机号),
new NameValuePair("content", "【短信模板】"),
};
method.setRequestBody(data);
try {
client.executeMethod(method);
System.out.println(method.getResponseBodyAsString());
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
第三步 ,在对应的service实现层编写对应的代码调用(我这里只传手机号,验证码在service实现层设置)
@Override
public ActionResult generateAuthCode(String telephone) {
if (!RegexUtil.isMobileExact(telephone)) {
return new ActionResult(StatusCode.MOBILE_FORMAT_ERROR);
}
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 6; i++) {
sb.append(random.nextInt(10));
}
//验证码
String authCode = sb.toString();
//发送验证码调用工具类的方法将手机号和验证码发过去
HttpClientUtil httpClientUtil =new HttpClientUtil();
httpClientUtil.getPost(telephone,authCode);
//验证码绑定手机号并存储到redis
redisService.set(REDIS_KEY_PREFIX_AUTH_CODE + telephone, sb.toString());
redisService.expire(REDIS_KEY_PREFIX_AUTH_CODE + telephone, AUTH_CODE_EXPIRE_SECONDS);
return new ActionResult(StatusCode.SUCCESS);
}
第四步,启动测试
【阿里巴巴】尊敬的用户,您的注册会员动态密码为:708257,请勿泄漏于他人!
验证成功