Springboot集成SMS发送短信

目前大多网站APP的登陆方式都不再单一,通过手机获取短信验证码进行账户登陆无疑是最方便、快捷和安全的一种方式。

第三方短信发送平台有很多种,各个平台有各自的优缺点,在选择的时候可以根据自己的具体实际情况定夺,今天LZ分享一个比较好上手的平台供广大码农借鉴,并非打广告,只是感觉真心好用。

LZ之前并不晓得SMS是什么鬼,只是去年在看一位大牛博主分享springboot案例的时候提到,对着大牛的步骤和代码操作了下去,顺利完成了短信发送的功能。最近刚好有个小小的需求要用到短信验证,去翻大牛的博客,竟然被关闭了,幸运的是有备份代码! 好东西应该分享出来,迎合开源精神 @#$!

【2】平台开通

2.1:用户注册

百度SMS短信通,进入官方页面,注册账号;
官网:http://sms.webchinese.cn/

2018-08-11_131642.png

2.2:登陆获取必要信息

2018-08-11_131836.png

登陆之后,首页会展示当前用户部分信息,这里只关注短信条数,新注册用户会有5条免费的测试短信,这里我们要记住的重要信息主要有5条,切记要保存好

1:账号名
2:密码
3:短信秘钥(验签秘钥,长度为20的加密字符串)
4:绑定手机:153xxxxxxxx
5:绑定邮箱:[email protected]

2018-08-11_132904.png

【3】代码实现

1、加入依赖

<dependencies>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.0.1</version>
        </dependency>
    </dependencies>

2、SendMessageUtil 工具类

/**
 * Created by lvfang on 2017/3/18.
 *
 * 短信发送工具类  SMS发送
 */
public class SendMessageUtil {

    private static final String SMS_Url = "http://sms.webchinese.cn/web_api/";

    /**
     * @param Uid SMS用户id  : lvfang123
     * @param Key 接口秘钥:SMS登录可查(非登录密码)
     * @param sendPhoneNum 短信发送目标号码
     * @param desc 短信内容
     * @return Integer(1:成功码,其他失败,具体参见注释)
     */
    public static Integer send(String Uid,String Key,String sendPhoneNum,String desc){

        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod(SMS_Url);
        post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码

        //设置参数
        NameValuePair[] data = {
                new NameValuePair("Uid", Uid),
                new NameValuePair("Key", Key),//秘钥
                new NameValuePair("smsMob", sendPhoneNum),
                new NameValuePair("smsText", desc)
        };

        post.setRequestBody(data);

        try {
            client.executeMethod(post);
        } catch (Exception e) {  e.printStackTrace();  }


        Header[] headers = post.getResponseHeaders();
        int statusCode = post.getStatusCode();
        System.out.println("statusCode:" + statusCode);
        for (Header h : headers) {
            System.out.println(h.toString());
        }

        String result ="";
        try {
            result = new String(post.getResponseBodyAsString().getBytes("gbk"));
        } catch (Exception e) {  e.printStackTrace();  }

        post.releaseConnection();

        return Integer.parseInt(result);
    }
    /**
     *  -1  没有该用户账户
     -2 接口密钥不正确 [查看密钥]不是账户登陆密码
     -21    MD5接口密钥加密不正确
     -3 短信数量不足
     -11    该用户被禁用
     -14    短信内容出现非法字符
     -4 手机号格式不正确
     -41    手机号码为空
     -42    短信内容为空
     -51    短信签名格式不正确接口签名格式为:【签名内容】
     -6 IP限制
     大于0    短信发送数量
     以上作为补充
     */
    public static String getMessage(Integer code){
        String message;
        if(code > 0 ) {
            message = "SMS-f发送成功!短信量还有" + code + "条";
        }else if(code == -1){
            message = "SMS-没有该用户账户";
        }else if(code == -2){
            message = "SMS-接口密钥不正确";
        }else if(code == -21){
            message = "SMS-MD5接口密钥加密不正确";
        }else if(code == -3){
            message = "SMS-短信数量不足";
        }else if(code == -11){
            message = "SMS-该用户被禁用";
        }else if(code == -14){
            message = "SMS-短信内容出现非法字符";
        }else if(code == -4){
            message = "SMS-手机号格式不正确";
        }else if(code == -41){
            message = "SMS-手机号码为空";
        }else if(code == -42){
            message = "SMS-短信内容为空";
        }else if(code == -51){
            message = "SMS-短信签名格式不正确接口签名格式为:【签名内容】";
        }else if(code == -6){
            message = "SMS-IP限制";
        }else{
            message = "其他错误";
        }
        return message;
    }

    /**
     * 随机生成6位验证码
     * @return
     */
    public static String getRandomCode(Integer code){
        Random random = new Random();
        StringBuffer result= new StringBuffer();
        for (int i=0;i<code;i++){
            result.append(random.nextInt(10));
        }
        return result.toString();
    }
}
   

3、全局测试

/**
     * 随机生成6位验证码
     * @return
     */
    public static String getRandomCode(){
        Random random = new Random();
        String result="";
        for (int i=0;i<6;i++){
            result+=random.nextInt(10);
        }
        return result;
    }

/**
     * @author:lvfang
     * @mathName: testSendMessage
     * @parameter: 无
     * @return value:
     * @throws null
     * @date 2018/8/11
     * @desc SMS短信测试
     */
    @Test
    public void testSendMessage(){
//        SendMessageUtil.send("SMS账户","接口秘钥","目标号码","发送内容");
        SendMessageUtil.send("lvfaxxxxxx","0b334927e1xxxxxxxxxx","153xxxxxxxxx","验证码:"+getRandomCode(6));
        System.out.println(SendMessageUtil.getMessage(resultCode));
    }

这里测试要注意的是,如果当前用户是测试用户(未交费绑定短信模板的用户),测试内容是受限的,并且短信未开通及时发送,程序所发送的短信是不能立刻收到的。具体详情请参照SMS官网注意事项。
新用户用接口测试验证码时,请勿输入:测试等无关内容信息,请直接输入:验证码:xxxxxx,发送。

4、发送响应
除了200响应码,其他都是有问题的, 这里贴个API调用接口文档:http://sms.webchinese.cn/api.shtml

statusCode:200
Cache-Control: no-cache
Content-Length: 2
Content-Type: text/html
Expires: Fri, 10 Aug 2018 05:39:58 GMT
Server: Microsoft-IIS/7.5
Set-Cookie: CHNET=Temp%5Fusername=201881113395989272; expires=Fri, 07-May-2021 05:39:58 GMT; path=/
Set-Cookie: ASPSESSIONIDAQBQTCCC=HDIPMIKCBOOOKHLDDPDKIAPI; path=/
X-Powered-By: ASP.NET
Date: Sat, 11 Aug 2018 05:40:00 GMT

##响应码文档
/**
     *  -1  没有该用户账户
        -2  接口密钥不正确 [查看密钥]不是账户登陆密码
        -21 MD5接口密钥加密不正确
        -3  短信数量不足
        -11 该用户被禁用
        -14 短信内容出现非法字符
        -4  手机号格式不正确
        -41 手机号码为空
        -42 短信内容为空
        -51 短信签名格式不正确接口签名格式为:【签名内容】
        -6  IP限制
        大于0 短信发送数量
        以上作为补充
     */

5、收到短信
不出意外、这时候我们就会收到自己发送的短信、

短信.png

6、回看短信日志

短信日志.png

这样我们就完成了一个简单的SMS短信发送案例,欢迎大家拍砖!!!



作者:先生_吕
链接:https://www.jianshu.com/p/fb1f90662a93
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

猜你喜欢

转载自blog.csdn.net/qq_25635139/article/details/85119186
今日推荐