依賴:commons-httpclient-3.1.jar、commons-codec-1.4.jar、commons-logging-1.1.1.jar
public class SendMsgWebchineseController {
public static Map<String, String> send(String phone) throws Exception {
Map<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;
}
}
@ResponseBody
@PostMapping("/register/sendCode")
public Response sendCode(@RequestBody UserBean user) {
String phone = user.getTelephone();
if (userService.existsByPhone(phone)) {
return Response.error("手機號已註冊");
}
try {
Map<String, String> res = SendMsgWebchineseController.send(phone);
if ("1".equals(res.get("result").trim())) {
request.getSession().setAttribute("smsCode", res.get("code"));
request.getSession().setMaxInactiveInterval(300);
return Response.success("發送成功");
}
} catch (Exception e) {
log.error("短信發送異常", e);
}
return Response.error("發送失敗,請稍後重試");
}
https://localhost:8080/register/sendCode{"telephone":"13800000000"}{"status":"SUCCESS","message":"發送成功"}MD5(code + salt),校驗比對摘要