手机短信验证码

使用网易云平台
注册账号

https://id.163yun.com/register?referrer=https://console.163yun.com

申请短信平台业务

可以说申请测试账号,每个账号20条测试短信

获取对应的应用信息

产品与服务 - - 点击 通信与视频 - 查询创建的应用

点击 App Key管理
获取 App Key 和 App Secret

点击 - 短信模板管理 - 验证码模板
获取 - 模板ID (默认是语言验证码) 短信验证码需要申请审核,通过后即可使用

实现代码

以下代码实现过程与工具类相似,作用是作为传递给 短信平台接口的参数。

public class CheckSumBuilder {
    // 计算并获取CheckSum
    public static String getCheckSum(String appSecret, String nonce, String curTime) {
        return encode("sha1", appSecret + nonce + curTime);
    }

    // 计算并获取md5值
    public static String getMD5(String requestBody) {
        return encode("md5", requestBody);
    }

    private static String encode(String algorithm, String value) {
        if (value == null) {
            return null;
        }
        try {
            MessageDigest messageDigest
                    = MessageDigest.getInstance(algorithm);
            messageDigest.update(value.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }
    
    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' 
    };
}
处理发送短信的服务端代码
public class SendCode extends HttpServlet {
    
    //发送验证码的请求路径URL (固定)
    private static final String
            SERVER_URL="https://api.netease.im/sms/sendcode.action";
    //网易云信分配的账号,请替换你在管理后台应用下申请的Appkey (个人账号申请)
    private static final String 
            APP_KEY="";
    //网易云信分配的密钥,请替换你在管理后台应用下申请的appSecret (个人账号申请)
    private static final String APP_SECRET="";
   
    //短信模板ID (对应个人账号的短信应用业务)
    private static final String TEMPLATEID="";

    //验证码长度,范围4~10,默认为4
    private static final String CODELEN="6";
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取客户端发送的手机号
        String tell = request.getParameter("phone_tell");
        
        Date d = new Date();
        long timeStemp =  d.getTime();
        String s = Long.toString(timeStemp);
        String s1 = s.substring(s.length()-6, s.length());
        
        
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(SERVER_URL);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        /*
         * 参考计算CheckSum的java代码,在上述文档的参数列表中,有CheckSum的计算文档示例
         */
        String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, s1, curTime);

        // 设置请求的header
        httpPost.addHeader("AppKey", APP_KEY);
        httpPost.addHeader("Nonce", s1);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        // 设置请求的的参数,requestBody参数
        List nvps = new ArrayList();
   
        nvps.add(new BasicNameValuePair("templateid", TEMPLATEID));
        nvps.add(new BasicNameValuePair("mobile", tell));
        nvps.add(new BasicNameValuePair("codeLen", CODELEN));

        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

        // 执行请求
        HttpResponse res = httpClient.execute(httpPost);
        /*
         *  短信平台返回的状态码
         * 1.打印执行结果,打印结果一般会200、315、403、404、413、414、500
         * 2.具体的code有问题的可以参考官网的Code状态表
         */
        
        String str = EntityUtils.toString(res.getEntity(), "utf-8");
        
        JSONObject jsonObject = JSONObject.parseObject(str);
        //验证码
        String code = jsonObject.getString("obj");
        System.out.println(code);
        
    }

}

你可能感兴趣的:(手机短信验证码)