方式一:
**使用第三方平台:**中国网建 SMS 短信通(http://sms.webchinese.com.cn/default.shtml)
1、注册
2、查看 API 接口
3、获取短信密钥
4、工具类:
SendMsgUtil.java
代码
package util;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import java.util.HashMap;
/**
* create by 1311230692@qq.com on 2018/10/9 09:04
* 发送验证码的工具类
**/
public class SendMsgUtil {
public static HashMap<String,String> getMessageStatus(String phone) throws Exception {
HashMap<String,String> hashMap = new HashMap<>();
// 连接第三方平台
PostMethod postMethod = new PostMethod("http://utf8.api.smschinese.cn/");
postMethod.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8"); // 在头文件中设置转码
// 生成随机字符的验证码
String randNum = String.valueOf(RandomUtil.getRandNum());
// 短信模板
NameValuePair[] data = {
new NameValuePair("Uid", "****"), // sms 短信通 注册的用户名
new NameValuePair("key", "*************"), // 密钥
new NameValuePair("smsMob", phone), // 要发送的目标手机号
new NameValuePair("smsText", "验证码:" + randNum + ",发送") // 自定义发送内容
};
for (NameValuePair n: data ) { // 打印信息方便调试
System.out.println("短信模板为:" + n);
}
postMethod.setRequestBody(data);
HttpClient client = new HttpClient();
client.executeMethod(postMethod);
// 获取 http 头
Header[] headers = postMethod.getRequestHeaders();
int statusCode = postMethod.getStatusCode();
System.out.println("statusCode:" + statusCode);
for (Header h: headers) { // 打印信息方便调试
System.out.println(h.toString());
}
// 获取返回消息
String result = new String(postMethod.getResponseBodyAsString().getBytes("utf-8"));
System.out.println(result);
// 将返回消息和 6 位数验证码放入 map 里面
hashMap.put("result",result);
hashMap.put("code",randNum);
// 断开第三方平台连接
postMethod.releaseConnection();
return hashMap;
}
}
获取随机 6 位数的验证码:
RandomUtil.java
代码:
package util;
/**
* create by 1311230692@qq.com on 2018/10/9 09:02
* 随机生成验证码工具类
**/
public class RandomUtil {
// 得到随机六位数
public static int getRandNum() {
return (int)((Math.random()*9+1)*100000);
}
}
控制层实现:
MessageController.java
代码:
package controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import entity.Phone;
import org.apache.commons.httpclient.HttpException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import service.MessageService;
import util.SendMsgUtil;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
/**
* create by 1311230692@qq.com on 2018/10/9 09:32
* 发送短信校验码控制层实现
*
**/
@Controller
@RequestMapping("/message")
public class MessageController {
/**
* 发送校验码
* @param phone 目标手机号
* */
@RequestMapping(value = "/send", method = RequestMethod.GET)
@ResponseBody
public String send(String phone, HttpServletRequest request) throws HttpException, Exception {
HashMap<String, String> map = SendMsgUtil.getMessageStatus(phone);
HashMap<String, String> hashMap = new HashMap<>(); // 用于存放返回结果
ObjectMapper objectMapper = new ObjectMapper();
String result = map.get("result");
HttpSession session = request.getSession(); // 设置 session
session.setMaxInactiveInterval(60 * 1); // 缓存设置 1 分钟内有效
if (result.trim().equals("1")) { // 标志位 1:成功
String code = map.get("code");
System.out.println("验证码为:" + code);
session.setAttribute("code",code); // 将收到的验证码放入 session 中
hashMap.put("result","success");
} else { // 标志位 0:失败
hashMap.put("result","fail");
}
return objectMapper.writeValueAsString(hashMap);
}
/**
* 比对校验码
* */
@RequestMapping(value = "/checkCode", method = RequestMethod.POST)
@ResponseBody
public String checkCode(String code, Phone phone, HttpServletRequest request) throws Exception{
HashMap<String, String> map = new HashMap<>();
ObjectMapper objectMapper = new ObjectMapper(); // json 转换函数
HttpSession session = request.getSession(); // 设置 session
String sessionCode = (String)session.getAttribute("code");
if ((code).equals(sessionCode)) { // 和缓存比对验证码是否相同
map.put("result", "success");
} else {
map.put("result", "fail");
}
return objectMapper.writeValueAsString(map);
}
}
方式二:
**使用第三方平台:**秒嘀科技(http://www.miaodiyun.com/home.html)
1、注册
2、查看 API
3、下载 DEMO
4、工具类:
Config.java
代码:
package util;
/**
* create by 1311230692@qq.com on 2018/10/9 13:14
* 使用秒嘀短信发送验证码
* 配置文件
**/
public class Config {
/**
* url 前半部分
* */
public static final String BASE_URL = "https://api.miaodiyun.com/20150822";
/**
* 开发者注册后系统自动生成的账号
*/
public static final String ACCOUNT_SID = "****************";
/**
* 开发者注册后系统自动生成的TOKEN
*/
public static final String AUTH_TOKEN = "*************";
/**
* 响应数据类型, JSON或XML
*/
public static final String RESP_DATA_TYPE = "json";
}
HttpUtil.java
代码:
package util;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* create by 1311230692@qq.com on 2018/10/9 13:24
* 秒嘀科技短信验证码
* http 请求工具类
**/
public class HttpUtil {
/**
* 构造通用参数timestamp、sig和respDataType
*
* @return
*/
public static String createCommonParam() {
// 时间戳
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String timestamp = sdf.format(new Date());
// 签名
String sig = DigestUtils.md5Hex(Config.ACCOUNT_SID + Config.AUTH_TOKEN + timestamp);
return "×tamp=" + timestamp + "&sig=" + sig + "&respDataType=" + Config.RESP_DATA_TYPE;
}
/**
* post请求
*
* @param url
* 功能和操作
* @param body
* 要post的数据
* @return
* @throws IOException
*/
public static String post(String url, String body) throws IOException {
System.out.println("url:" + System.lineSeparator() + url);
System.out.println("body:" + System.lineSeparator() + body);
String result = "";
try
{
OutputStreamWriter out = null;
BufferedReader in = null;
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
// 设置连接参数
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(20000);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 提交数据
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.write(body);
out.flush();
// 读取返回数据
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = "";
boolean firstLine = true; // 读第一行不加换行符
while ((line = in.readLine()) != null)
{
if (firstLine)
{
firstLine = false;
} else
{
result += System.lineSeparator();
}
result += line;
}
} catch (Exception e)
{
e.printStackTrace();
}
return result;
}
/**
* 回调测试工具方法
*
* @param url
* @param body
* @return
*/
public static String postHuiDiao(String url, String body)
{
String result = "";
try
{
OutputStreamWriter out = null;
BufferedReader in = null;
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
// 设置连接参数
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(20000);
// 提交数据
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.write(body);
out.flush();
// 读取返回数据
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = "";
boolean firstLine = true; // 读第一行不加换行符
while ((line = in.readLine()) != null)
{
if (firstLine)
{
firstLine = false;
} else
{
result += System.lineSeparator();
}
result += line;
}
} catch (Exception e)
{
e.printStackTrace();
}
return result;
}
}
IndustrySMS.java
代码
package util;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
/**
* create by 1311230692@qq.com on 2018/10/9 13:32
* 秒嘀科技短信验证码
* 验证码通知短信接口
**/
public class IndustrySMS {
private static String operation = "/industrySMS/sendSMS";
private static String accountSid = Config.ACCOUNT_SID;
private static String to = "";
private static String param = "";
private static String smsContent = "【易科技】尊敬的用户,您好,登录验证码:";
/**
* 验证码通知短信
*/
public static void execute() throws IOException {
HashMap<String, String> map = new HashMap<>();
// 生成验证码
param = String.valueOf(RandomUtil.getRandNum());
String tmpSmsContent = null;
try {
tmpSmsContent = URLEncoder.encode(smsContent + param + ",如非本人操作,请忽略此短信。", "UTF-8"); // 注意模板中的逗号是中文的
System.out.println(smsContent + param + ", 如非本人操作,请忽略此短信。");
} catch (Exception e){
}
System.out.println("生成验证码为:" + param);
String url = Config.BASE_URL + operation;
String body = "accountSid=" + accountSid + "&to=" + to + "&smsContent=" + tmpSmsContent
+ HttpUtil.createCommonParam();
// 提交请求
String result = HttpUtil.post(url, body);
System.out.println("result:" + System.lineSeparator() + result);
String status = result.substring(12,18);
System.out.println("status:" + status);
}
public static HashMap<String, String> executeHash(String phone) throws Exception {
HashMap<String, String> map = new HashMap<>();
// 生成验证码
param = String.valueOf(RandomUtil.getRandNum());
String tmpSmsContent = null;
try {
tmpSmsContent = URLEncoder.encode(smsContent + param + ",如非本人操作,请忽略此短信。", "UTF-8"); // 注意模板中的逗号是中文的
System.out.println(smsContent + param + ", 如非本人操作,请忽略此短信。");
} catch (Exception e){
}
String url = Config.BASE_URL + operation;
String body = "accountSid=" + accountSid + "&to=" + phone + "&smsContent=" + tmpSmsContent
+ HttpUtil.createCommonParam();
// 提交请求
String result = HttpUtil.post(url, body);
System.out.println("result:" + System.lineSeparator() + result);
String status = result.substring(13,18);
map.put("respCode", status);
map.put("checkCode",param);
return map;
}
}
控制层代码实现;
MiaoDiController.java
代码:
package controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import util.IndustrySMS;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
/**
* create by 1311230692@qq.com on 2018/10/9 13:22
* 第三方平台使用秒嘀科技
* 控制层实现
**/
@Controller
@RequestMapping("/miao")
public class MiaoDiController {
/**
* 发送验证码
* */
@RequestMapping(value = "/send", method = RequestMethod.GET)
@ResponseBody
public String send(String phone, HttpServletRequest request) throws Exception{
HashMap<String, String> map = IndustrySMS.executeHash(phone);
ObjectMapper objectMapper = new ObjectMapper();
String status = map.get("respCode");
String checkCode = map.get("checkCode");
// 将验证码缓存到 session 中
HttpSession session = request.getSession();
session.setMaxInactiveInterval(60 * 1); // 设置 session 一分钟内有效,单位是秒
if (status.trim().equals("00000")) {
map.put("result", "00000");
session.setAttribute("checkCode",checkCode);
} else if(status.trim().equals("00141")) {
map.put("result", "00141");
} else {
map.put("result","fail");
}
return objectMapper.writeValueAsString(map);
}
/**
* 比对校验码
* */
@RequestMapping(value = "/checkCode", method = RequestMethod.POST)
@ResponseBody
public String checkCode(String code, HttpServletRequest request) throws Exception{
HashMap<String, String> map = new HashMap<>();
ObjectMapper objectMapper = new ObjectMapper();
HttpSession session = request.getSession(); // 设置 session
String sessionCode = (String)session.getAttribute("checkCode");
if ((code).equals(sessionCode)) { // 和缓存比对验证码是否相同
map.put("result", "success");
} else {
map.put("result", "fail");
}
return objectMapper.writeValueAsString(map);
}
}
备注:使用秒嘀科技新建短信模板时,提供的模板中的逗号是中文的
,免费短信较多,可用于调试,费用较低,技术支持到位,推荐使用。
版权声明:欢迎转载, 转载请保留原文链接。