SendMsg_webchineseController依賴:commons-httpclient-3.1.jar、commons-codec-1.4.jar、commons-logging-1.1.1.jar
public class SendMsg_webchineseController {
public static HashMap<String, String> getMessageStatus(String phone) throws Exception {
HashMap<String, String> result = new HashMap<>();
HttpClient client = new HttpClient();
PostMethod post = new PostMethod("https://gbk.sms.webchinese.cn");
post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");
String code = VerifyingCodeGenerator.generate(); // 自定義 6 位隨機數生成器
NameValuePair[] data = {
new NameValuePair("Uid", "你的用戶名"),
new NameValuePair("Key", "你的密鑰"),
new NameValuePair("smsMob", phone),
new NameValuePair("smsText", "您正在註冊本站會員,本次驗證碼為:" + code + " 無效時間為5分鐘")
};
result.put("code", code);
post.setRequestBody(data);
client.executeMethod(post);
String resp = new String(post.getResponseBodyAsString().getBytes("gbk"));
result.put("result", resp); // "1" 表示成功,其他為失敗
post.releaseConnection();
return result;
}
}
SendCheckMessage@ResponseBody
@RequestMapping(value = UrlDefine.Register.CHECKMESSAGEWORK, method = RequestMethod.POST)
public Object SendCheckMessage(HttpServletRequest request, @RequestBody UserBean u) throws Exception {
String phone = u.getTelephone();
if (userService.getByPhone(phone) != null) {
return new Response(Status.ERROR, "該手機號已被註冊");
}
HashMap<String, String> m = SendMsg_webchineseController.getMessageStatus(phone);
if ("1".equals(m.get("result").trim())) {
HttpSession session = request.getSession();
session.setAttribute("code", m.get("code"));
session.setMaxInactiveInterval(60 * 5); // 5 分鐘
return new Response(Status.SUCCESS, "發送成功");
}
return new Response(Status.ERROR, "短信發送失敗");
}
使用 Postman POST JSON {"telephone":"13800000000"},返回 {"status":"SUCCESS","message":"發送成功"},手機端收到驗證碼短信。