网易云信发送短信工具类

314 阅读10分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

要求: 1.账号权限要求 您先有网易云信账号,已经开通好了具体应用,附上了短信权限,开通好了短息模板。 这个条件就绪后,您有: 应用下申请的Appkey、网易云信分配的密钥appSecret、短信模板TEMPLATEID 2.官方jar包 网易云信发送短信之前,需要本地项目引入其官方的jar包 以maven项目为例,具体引入环节参照: 这篇博客

引入完成后: 网易云信常用接口:发送验证码、校验验证码、发送通知类信息。 为了满足不同场景下使用,方便大家测试,把这三个时间整合三个独立的,然后第四段我们整合成一个,具体用那个方便,自行选择。

强烈推荐第四个代码片 理由如下: 整合了发送短信消息、发送验证码、短信校验码。 修复了官方提供代码片中过时的 DefaultHttpClient httpClient = new DefaultHttpClient();写法。 针对有阿里代码规范要求的做了调整。 直接粘贴复制 配参数可用!
一句话,它香啊!

【网易云信验证码】封装类以及测试:

package com.项目路径.util;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: auth
 * @description: 短信验证码
 **/
public final class SmsCodeUtil {

    public SmsCodeUtil() {
        throw new AssertionError();
    }

    //发送验证码的请求路径URL
    private static final String serverUrl = "https://api.netease.im/sms/sendcode.action";
    //网易云信分配的账号 						
    private static final String appKey = "这里是一个36位的appKey";
    //网易云信分配的密钥
    private static final String appSecret = "这里是一个12位的appSecret";
    //随机数
    private static final String nonce = "123456";
    //短信模板ID
    private static final String templateid = "这里是一个12位的templateid";
    //验证码长度,范围4~10,默认为4
    private static final String codelen = "4";

    public static String sendSmsCode(String phone) throws ClientProtocolException, IOException {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(serverUrl);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);

        String checkSum = getCheckSum(appSecret, nonce, curTime);

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

        // 设置请求的的参数,requestBody参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        /*
         * 1.如果是模板短信,请注意参数mobile是有s的,详细参数配置请参考“发送模板短信文档”
         * 2.参数格式是jsonArray的格式,例如 "['13888888888','13666666666']"
         * 3.params是根据你模板里面有几个参数,那里面的参数也是jsonArray格式
         */
        nvps.add(new BasicNameValuePair("templateid", templateid));
        nvps.add(new BasicNameValuePair("mobile", phone));
        nvps.add(new BasicNameValuePair("codeLen", codelen));

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

        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);
        /*
         * 1.打印执行结果,打印结果一般会200、315、403、404、413、414、500
         * 2.具体的code有问题的可以参考官网的Code状态表
         */
        String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");

        //获取发送状态码
        String code = JSON.parseObject(responseEntity).getString("code");
        return code;

    }

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

    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 static void main(String[] args) throws ClientProtocolException, IOException {
        sendSmsCode("155*******0");
    }
}

【网易云信校验验证码】封装类以及测试:

package com.项目路径.util;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @program: auth
 * @description: 短信验证码校验
 **/
public final class SmsVerifyCodeUtil {

    public SmsVerifyCodeUtil() {
        throw new AssertionError();
    }

    //校验验证码的请求路径URL
    private static final String serverUrl = "https://api.netease.im/sms/verifycode.action";
    //网易云信分配的账号 
    private static final String appKey = "appKey ";
    //网易云信分配的密钥
    private static final String appSecret = "appSecret ";
    //随机数
    private static final String nonce = "123456";


    public static String checkMsg(String phone, String sum) throws ClientProtocolException, IOException {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(serverUrl);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = getCheckSum(appSecret, nonce, curTime);


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

        // 设置请求的的参数,requestBody参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        nvps.add(new BasicNameValuePair("mobile", phone));
        nvps.add(new BasicNameValuePair("code", sum));

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

        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);
        /*
         * 1.打印执行结果,打印结果一般会200、315、403、404、413、414、500
         * 2.具体的code有问题的可以参考官网的Code状态表
         */
        String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");

        //获取发送状态码
        String code = JSON.parseObject(responseEntity).getString("code");


        System.out.println(code);
        if (code.equals("200")) {

            return "success";
        }
        return "error";


    }

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

    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 static void main(String[] args) throws ClientProtocolException, IOException {
        checkMsg("15502293820", "7559");
    }


}

【网易云信短息通知信息】封装类以及测试:

package com.项目路径.util;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: auth
 * @description: 短信通知类
 **/
public final class SmsMsgUtil {

    public SmsMsgUtil() {
        throw new AssertionError();
    }

    //发送短信通知的请求路径URL
    private static final String serverUrl = "https://api.netease.im/sms/sendtemplate.action";
    //网易云信分配的账号 						
    private static final String appKey = "appKey ";
    //网易云信分配的密钥
    private static final String appSecret = "appSecret";
    //随机数
    private static final String nonce = "123456";
    //短信模板ID
    private static final String templateid = "templateid ";
    /**
     *
     * @param mobiles
     * 如:String mobiles="['155*******0']";
     * 手机号,接收者号码列表,JSONArray格式,限制接收者号码个数最多为100个
     * @param params
     * 如:String params="['Hi,Goods Boy']";
     * 短信参数列表,用于依次填充模板,JSONArray格式,每个变量长度不能超过30字,对于不包含变量的模板,不填此参数表示模板即短信全文内容
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String sendSmsMsg(String mobiles,String params) throws ClientProtocolException, IOException {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(serverUrl);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);

        String checkSum = getCheckSum(appSecret, nonce, curTime);

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

        // 设置请求的的参数,requestBody参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        /*
         * 1.如果是模板短信,请注意参数mobile是有s的,详细参数配置请参考“发送模板短信文档”
         * 2.参数格式是jsonArray的格式,例如 "['13888888888','13666666666']"
         * 3.params是根据你模板里面有几个参数,那里面的参数也是jsonArray格式
         */
        nvps.add(new BasicNameValuePair("templateid", templateid));
        nvps.add(new BasicNameValuePair("mobiles", mobiles));
        nvps.add(new BasicNameValuePair("params", params));

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

        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);
        /*
         * 1.打印执行结果,打印结果一般会200、315、403、404、413、414、500
         * 2.具体的code有问题的可以参考官网的Code状态表
         */
        String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");
        //获取发送状态码
        String code = JSON.parseObject(responseEntity).getString("code");
        return code;

    }

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

    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 static void main(String[] args) throws ClientProtocolException, IOException {
        sendSmsMsg("['155*******0']","['恭喜,你又收到我的测试短信了!']");
    }
}

【整合:网易云信 发送验证码、校验验证码、发送短息通知信息】封装类以及测试:

package com.项目路径.util;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 网易云信发送短信、验证码、校验验证码
 * @author zhaoxinglu
 */
public final class SmsWyyxUtil {

    public SmsWyyxUtil() {
        throw new AssertionError();
    }

    /**
     * 网易云信分配的账号
     */
    private static final String APP_KEY = "APP_KEY ";
    /**
     * 网易云信分配的密钥
     */
    private static final String APP_SECRET = "APP_SECRET ";
    /**
     * 随机数
     */
    private static final String NONCE = "NONCE ";

    /**
     * 发送短息通知信息配置参数 - 请求路径URL
     */
    private static final String SERVER_MSG = "https://api.netease.im/sms/sendtemplate.action";
    /**
     * 发送短息通知信息配置参数 - 短信模板
     */
    private static final String TEMPLATE_ID_MSG = "短信模板ID";

    /**
     * 发送短信验证码配置参数 - 请求路径URL
     */
    private static final String SERVER_CODE = "https://api.netease.im/sms/sendcode.action";
    /**
     * 发送短信验证码配置参数 - 短信模板
     */
    private static final String TEMPLATE_ID_CODE = "短信模板ID";
    /**
     * 发送短信验证码配置参数 - 验证码长度,范围4~10,默认为4
     */
    private static final String CODE_LEN = "4";

    /**
     * 校验验证码配置参数 - 请求路径URL
     */
    private static final String SERVER_VERIFY_CODE = "https://api.netease.im/sms/verifycode.action";

    /**
     * 成功值
     */
    private static final String SUCCESS = "200";

    /**
     * 发送信息通知
     *
     * @param mobiles 如:String mobiles="['15502293820']";
     *                手机号,接收者号码列表,JSONArray格式,限制接收者号码个数最多为100个
     * @param params  如:String params="['Hi,Goods Boy']";
     *                短信参数列表,用于依次填充模板,JSONArray格式,每个变量长度不能超过30字,对于不包含变量的模板,不填此参数表示模板即短信全文内容
     * @return true 发送成功 false失败
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static Boolean sendSmsMsg(String mobiles, String params) throws ClientProtocolException, IOException {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(SERVER_MSG);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = getCheckSum(APP_SECRET, NONCE, curTime);

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

        // 设置请求的的参数,requestBody参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("templateid", TEMPLATE_ID_MSG));
        nvps.add(new BasicNameValuePair("mobiles", mobiles));
        nvps.add(new BasicNameValuePair("params", params));

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

        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);

        String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");
        //获取发送状态码
        String code = JSON.parseObject(responseEntity).getString("code");

        if(SUCCESS.equals(code)) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 发送短信验证码
     *
     * @param phone 发送手机号
     * @return  true 发送成功 false失败
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static Boolean sendSmsCode(String phone) throws ClientProtocolException, IOException {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(SERVER_CODE);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = getCheckSum(APP_SECRET, NONCE, curTime);

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

        // 设置请求的的参数,requestBody参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        nvps.add(new BasicNameValuePair("templateid", TEMPLATE_ID_CODE));
        nvps.add(new BasicNameValuePair("mobile", phone));
        nvps.add(new BasicNameValuePair("codeLen", CODE_LEN));

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

        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);
        String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");

        //获取发送状态码
        String code = JSON.parseObject(responseEntity).getString("code");

        if(SUCCESS.equals(code)) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 校验验证码
     *
     * @param phone 校验手机号
     * @param sum   验证码
     * @return  true 校验成功 false校验失败
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static Boolean verifyCode(String phone, String sum) throws ClientProtocolException, IOException {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(SERVER_VERIFY_CODE);
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = getCheckSum(APP_SECRET, NONCE, curTime);

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

        // 设置请求的的参数,requestBody参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();

        nvps.add(new BasicNameValuePair("mobile", phone));
        nvps.add(new BasicNameValuePair("code", sum));

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

        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);
        String responseEntity = EntityUtils.toString(response.getEntity(), "utf-8");

        //获取发送状态码
        String code = JSON.parseObject(responseEntity).getString("code");
        System.out.println("校验发送状态码:" + code);
        if(SUCCESS.equals(code)) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 计算并获取CheckSum
     * @param appSecret
     * @param nonce
     * @param curTime
     * @return
     */
    private static String getCheckSum(String appSecret, String nonce, String curTime) {
        return encode("sha1", appSecret + nonce + curTime);
    }

    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 static void main(String[] args) throws ClientProtocolException, IOException {
        //测试发送通知信息
        //sendSmsMsg("['155*******0']","['恭喜,你又收到我的测试短信了!']");

        //测试发送验证码
        //sendSmsCode("155*******0");

        //测试校验验证码
        verifyCode("155*******0", "7559");

    }



}