1.在配置文件制定短信网关信息
sms.username=xmg sms.password=1111 sms.apikey=1111 #模拟短信网关 sms.url=http://localhost:8082/send.do
2.在JAVA代码中
@Value("${sms.username}") private String username; @Value("${sms.password}") private String password; @Value("${sms.apikey}") private String apiKey; @Value("${sms.url}") private String url;
//发送短信 //System.out.println("给手机 "+phoneNumber+"发送验证码:"+verifyCode); //通过URL 得到一个HTTPURLConnetion连接对象 try { //创建一个URL对象 URL url = new URL(this.url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //拼接POST请求的内容 StringBuilder content = new StringBuilder(100) .append("username=").append(username) .append("&password=").append(password) .append("&apikey=").append(apiKey) .append("&mobile=").append(phoneNumber)//手机号 .append("&content=") .append("验证码是:").append(verifyCode).append(",请在5分钟内使用");//验证码 //发送post请求,POST或者GET一定要大写 conn.setRequestMethod("POST"); //设置POST请求是有请求体的 conn.setDoOutput(true); //写入post请求体 conn.getOutputStream().write(content.toString().getBytes()); //得到响应流(其实就已经发送了) String response = StreamUtils.copyToString(conn.getInputStream(), Charset.forName("UTF-8")); if (response.startsWith("success:")) { //发送成功 //把手机号码 验证码 发送时间 装配到Vo中 并保存到session vc = new VerifyCodeVO(); vc.setLastSendTime(new Date()); vc.setPhoneNumber(phoneNumber); vc.setVerifyCode(verifyCode); UserContext.putVerifyCode(vc); }else { //发送失败 throw new RuntimeException(); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("短信发送失败"); }