spring boot + maven +秒嘀科技 实现发送短信功能

目录结构:spring boot + maven +秒嘀科技 实现发送短信功能_第1张图片

pom.xml:

xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>com.messagegroupId>
    <artifactId>sendMessageartifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>jarpackaging>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <maven.compiler.source>1.8maven.compiler.source>
        <maven.compiler.target>1.8maven.compiler.target>
    properties>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>1.5.9.RELEASEversion>
    parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.11version>
            <scope>testscope>
        dependency>
        
        <dependency>
            <groupId>net.sf.json-libgroupId>
            <artifactId>json-libartifactId>
            <version>2.4version>
            <classifier>jdk15classifier>
        dependency>

    dependencies>
    <build>
        <finalName>SMSfinalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>
project>
工具类:

package com.message.util;

import java.util.Random;

/**
 * 获取6位随机数
 */
public class RandUtil {

    public  static String  getRandomNum(){
        Random random=new Random();
        String randomNum = random.nextInt(1000000) + "";
        if(randomNum.length()!=6){
            System.out.println("6位伪随机数:"+randomNum);
            return  getRandomNum();
        }
        System.out.println("6位随机数:"+randomNum);
        return randomNum;
    }

}

package com.message.util;

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

public class SendNumUtil {
    /**
     * 获取时间戳工具
     *
     * @return
     */
    public static String getTimeStamp() {

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        String timeStamp = format.format(date);
        System.out.println("时间戳:"+timeStamp);
        return timeStamp;

    }

    /**
     * 发送验证码
     *
     * @param ACCOUNT_SID
     * @param AUTH_TOKEN
     * @param smsContent
     * @param to
     * @return
     */
    public static String queryArgs(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+"×tamp="+timeStamp+"&sig="+sig;
        System.out.println("参数:"+str);
        return str;

    }

    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();
    }
}
 
  
package com.message.util;

import net.sf.json.JSONObject;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class GetSMS {
    /**
     * 用户ID
     */
    public static final String ACCOUNT_SID = "837f0008f2134b3294d31bdeeab18d36";//这里填写你在平台里的ACOUNT_SID

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

    /**
     * 请求地址前半部分
     */
    public static final String BASE_URL = "https://api.miaodiyun.com/20150822/industrySMS/sendSMS";//请求地址是固定的不用改
    /**
     * 随机码
     */
    public static String randNum = RandUtil.getRandomNum();
    public static String smsContent = "【联营科技】您的验证码为" + randNum + ",请于" + 2 + "分钟内正确输入,如非本人操作,请忽略此短信。";

    /**
     * 获取验证码
     *
     * @param to
     * @return
     */
    public static String getmMssage(String to) {
        String args = SendNumUtil.queryArgs(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 (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.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"));
        return jsonObject.toString();
//        if (!object.equals("00000")) {
//            return object.toString();
//        }else{
//            return "发送成功!";
//        }
    }

    //测试功能
//  public static void main(String[] args) {
//     String result = getmMssage("15039925857");
//    System.out.println("验证码:"+randNum+"\t"+result);
// }
}
controller层:

package com.message.controller;

import com.message.util.GetSMS;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SendMessage {

    @RequestMapping(value = "/hello")
    public String index(){
        return "hello!";
    }
    @RequestMapping(value = "/sms/{to}")
    public String sendSMS(@PathVariable String to){
        return GetSMS.getmMssage(to);
    }
}
启动入口类:
package com.message;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}
运行效果:

在浏览器输入:localhost:8080/sms/15039925857          (15039925857是接收的手机号!)


你可能感兴趣的:(spring boot + maven +秒嘀科技 实现发送短信功能)