码迷,mamicode.com
首页 > 其他好文 > 详细

发送短信

时间:2018-03-17 19:46:58      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:bytes   pos   uil   手机号码   代码   ace   system   code   post   

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("短信发送失败");
            }

 

发送短信

标签:bytes   pos   uil   手机号码   代码   ace   system   code   post   

原文地址:https://www.cnblogs.com/jokerq/p/8591997.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!