java实现发送短信验证码

  • A+
所属分类:java 编程

在网站开发中的注册模块中,短信接收验证码是大部分网站必不可少的功能。这里我就简单总结了一下实现发送短信验证码的功能。

这里用的是秒滴短信服务平台。新用户注册给200条短信,测试够用了。

下面直接上实现代码吧,我这里主要是用作记录笔记大家也可以参考一下。

用到的pom文件:


      4.0.0
      com.hxkj.com
      hellohao01
      0.0.1-SNAPSHOT
      war
      hellohao01

        UTF-8

        commons-beanutils
        commons-beanutils
        1.8.0

        commons-logging
        commons-logging
        1.1.1

        commons-collections
        commons-collections
        3.2

        commons-lang
        commons-lang
        2.4

        net.sf.ezmorph
        ezmorph
        1.0.6

        net.sf.json-lib
        json-lib
        2.4
        jdk15

          javax
          javaee-api
          7.0
          provided

          org.glassfish.web
          javax.servlet.jsp.jstl
          1.2.2

            maven-compiler-plugin
            2.3.2

              1.7
              1.7

            maven-war-plugin
            2.2

              3.1
              false

创建一个RandUtil类,用于生成验证码:

    package org.hellohao.ustil;

    import java.util.Random;

    public class RandUtil {
         public static String getRandNum() {
                String randNum = new Random().nextInt(1000000)+"";
                System.out.println("生成"+randNum);
                if (randNum.length()!=6) {   //如果生成的不是6位数随机数则返回该方法继续生成
                    return getRandNum();
                }
                return randNum;
            }

    }

创建QueryUtil类:


    package org.hellohao.ustil;

    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class QueryUtil {

    public static String queryArguments(String ACCOUNT_SID,String AUTH_TOKEN, String smsContent,String to) {

        String timestamp = getTimestamp(); //时间戳
        String sig =  MD5(ACCOUNT_SID,AUTH_TOKEN,timestamp);//签名认证

        String str = "accountSid="+ACCOUNT_SID+"&smsContent="+
                smsContent+"&to="+to+"&timestamp="+timestamp+"&sig="+sig;
        return str;
    }
    /**
     * MD5加密
     * @param args
     * @return
     */
    public static String MD5(String... args){ //动态参数
        StringBuffer result = new StringBuffer();
        if (args == null || args.length == 0) {
            return "";
        } else {
            StringBuffer str = new StringBuffer();
            for (String string : args) {
                str.append(string);
            }
            System.out.println("加密前:\t"+str.toString());

            try {
                MessageDigest digest = MessageDigest.getInstance("MD5");
                byte[] bytes = digest.digest(str.toString().getBytes());
                for (byte b : bytes) {
                    String hex = Integer.toHexString(b&0xff);  //转化十六进制
                    if (hex.length() == 1) {
                        result.append("0"+hex);
                    }else{
                        result.append(hex);
                    }
                }

            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        System.out.println("加密后:\t"+result.toString());
        return result.toString();
    }
    /*
     * 获取时间戳
     */
    public static String getTimestamp(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        return sdf.format(date);
    }

}

创建实现发送短信的类GetMessage:

    package org.hellohao.ustil;

    import net.sf.json.JSONObject;

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.URL;
    import java.net.URLConnection;

    public class GetMessage {
        static String user="张三";

    /**
     * 用户ID
     */
    public static final String ACCOUNT_SID = "xxxxxx";//这里填写你在平台里的ACOUNT_SID

    /**
     * 密钥
     */
    public static final String AUTH_TOKEN = "xxxxxx";

    /**
     * 请求地址前半部分
     */
    public static final String BASE_URL = "https://api.miaodiyun.com/20150822/industrySMS/sendSMS";//请求地址是固定的不用改

    public static  String randNum = RandUtil.getRandNum();

    public  static String smsContent = "【世豪有限公司】亲爱的"+user+",您的验证码为"+randNum+",请于"+2+"分钟内正确输入,如非本人操作,请忽略此短信。";
    /**
     * (获取短信验证码)
     * @param to
     * @return String
     */
    public static String getResult(String to) {
        randNum = RandUtil.getRandNum();
        String smsContent = "【世豪有限公司】亲爱的"+user+",您的验证码为"+randNum+",请于"+2+"分钟内正确输入,如非本人操作,请忽略此短信。";            //这里的randNum 和 smsContent和上面的静态变量是一样的,可删除可保留
        String args = QueryUtil.queryArguments(ACCOUNT_SID, AUTH_TOKEN, smsContent, to);
        OutputStreamWriter out = null;
        InputStream in = null;
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();

        try {
            URL url = new URL(BASE_URL);
            URLConnection connection = url.openConnection(); //打开链接
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(5000);  //设置链接超时
            connection.setReadTimeout(10000);    //设置读取超时

            //提交数据
            out = new OutputStreamWriter(connection.getOutputStream(),"utf-8");
            out.write(args);
            out.flush();

            //读取返回数据
            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            while((line = br.readLine())!=null){
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (br!=null) {
                    br.close();
                }
                if (out!=null) {
                    out.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        JSONObject jsonObject = JSONObject.fromObject(sb.toString());
        System.out.println(jsonObject);
        Object object = jsonObject.get("respCode");
        System.out.println("状态码:"+object+"验证码:"+randNum);
        System.out.println(!object.equals("00000"));
        if (!object.equals("00000")) {
            return object.toString();
        }else{

            return randNum;
        }
    }
    //  测试功能
      public static void main(String[] args) {
      String result = getResult("15555555555");  //这里填写要接受验证码的手机号
      System.out.println("验证码:"+randNum+"\t"+result);   
      }
    }

--END--

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: