JEECG3.3.0配置旦米和创云短信

JEECG配置旦米短信(没有实际账号,只是测出来用户名不存在)
在yml文件中配置以下内容

  #    旦米短信
dmsms:
  accountSid: ??
  authToken: ??

创建DmSmsHelper类和DmHttpUtil类(http请求工具)

import org.apache.commons.codec.digest.DigestUtils;

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

/**
 * http请求工具
 */
public class DmHttpUtil {
    /**
     * 构造通用参数timestamp、sig和respDataType
     *
     * @return
     */
    public static String createCommonParam(String sid,String token,String datetype) {
        // 时间戳
        long timestamp = System.currentTimeMillis();
        // 签名
        String sig = DigestUtils.md5Hex(sid + token + timestamp);

        // return "&timestamp=" + timestamp + "&sig=" + sig + "&respDataType=" + Config.RESP_DATA_TYPE;
        return "&timestamp=" + timestamp + "&sig=" + sig + "&respDataType="+datetype;
    }

    /**
     * post请求
     *
     * @param url
     *            功能和操作
     * @param body
     *            要post的数据
     * @return
     * @throws IOException
     */
    public static String post(String url, String body) {
        System.out.println("body:" + System.lineSeparator() + body);

        String result = "";
        try {
            OutputStreamWriter out = null;
            BufferedReader in = null;
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();

            // 设置连接参数
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(20000);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 提交数据
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(body);
            out.flush();

            // 读取返回数据
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line = "";
            boolean firstLine = true; // 读第一行不加换行符
            while ((line = in.readLine()) != null) {
                if (firstLine) {
                    firstLine = false;
                } else {
                    result += System.lineSeparator();
                }
                result += line;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 回调测试工具方法
     *
     * @param url
     * @return
     */
    public static String postHuiDiao(String url, String body) {
        String result = "";
        try {
            OutputStreamWriter out = null;
            BufferedReader in = null;
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();

            // 设置连接参数
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(20000);

            // 提交数据
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(body);
            out.flush();

            // 读取返回数据
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line = "";
            boolean firstLine = true; // 读第一行不加换行符
            while ((line = in.readLine()) != null) {
                if (firstLine) {
                    firstLine = false;
                } else {
                    result += System.lineSeparator();
                }
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

```java
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.util.DmHttpUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.config.StaticConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.util.Map;

/**
 * cuiqingwei-insert date:2022.8.30 for:新增旦米短信,后期根据需求更改
 * 旦米短信
 */
public class DmSmsHelper {

    private final static Logger logger= LoggerFactory.getLogger(DmSmsHelper.class);

    /**TODO 此处需要替换成开发者自己的*/
    static  String accountSid;
    static  String authToken;


    /**url前半部分*/
     static final String BASE_URL = "https://openapi.danmi.com/distributor/sendSMS";
    /**响应数据类型, JSON或XML*/
    public static final String RESP_DATA_TYPE = "JSON";

    public static String getAccountSid() {
        return accountSid;
    }

    public static void setAccountSid(String accountSid) {
        DmSmsHelper.accountSid = accountSid;
    }

    public static String getAuthToken() {
        return authToken;
    }

    public static void setAuthToken(String authToken) {
        DmSmsHelper.authToken = authToken;
    }

    public static boolean dmSetSms(String phones,String smsparam,String templateid) throws Exception {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //update-begin-author:taoyan date:20200811 for:配置类数据获取
        StaticConfig staticConfig = SpringContextUtils.getBean(StaticConfig.class);
        setAccountSid(staticConfig.getAccountSid());
        setAuthToken(staticConfig.getAuthToken());
        //update-end-author:taoyan date:20200811 for:配置类数据获取
        Map<String, Object> requestBody  = JSONObject.parseObject(DmHttpUtil.post(BASE_URL, assembleSmsparam(phones, smsparam, templateid)
                +DmHttpUtil.createCommonParam(accountSid, authToken, RESP_DATA_TYPE)));
        logger.info("短信接口返回的数据----------------");
        return true;
    }

    public static String assembleSmsparam(String phones,String smsparam,String templateid) throws Exception {
        StringBuilder sb = new StringBuilder();
        sb.append("accountSid").append("=").append(accountSid);
        sb.append("&to").append("=").append(phones);//手机号
        sb.append("&param").append("=").append(URLEncoder.encode(smsparam,"UTF-8"));//短信变量
        sb.append("&templateid").append("=").append("1251");//短信模板id
        // sb.append("&templateid").append("=").append(templateid);//短信模板id
        return sb.toString();
    }


}

配置完成,通过接口访问即可
{“respDesc”:“用户不存在”,“respCode”:“0020”}
因为没有账号所以只能到此结束

配置创云
在yml文件中添加以下代码

cysms:
  account: ??
  password: ??

在这里插入图片描述
在这里插入图片描述
创建CySms类

import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.config.StaticConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * cuiqingwei-insert date:2022.8.30 for: 创云SMS
 * 创云SMS
 */
@Controller
@RequestMapping("CySms")
public class CySms {
    private final static Logger logger= LoggerFactory.getLogger(DmSmsHelper.class);


    /**TODO 此处需要替换成开发者自己的*/
    static  String account;
    static  String password;
    static  String SERVERURL = "http://xxx.253.com/msg/send/json";
    public static String getAccount() {
        return account;
    }

    public static void setAccount(String account) {
        CySms.account = account;
    }

    public static String getPassword() {
        return password;
    }

    public static void setPassword(String password) {
        CySms.password = password;
    }
    @RequestMapping("sendCysms")
    public static boolean sendCysms(String phone,String msg){
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        StaticConfig staticConfig = SpringContextUtils.getBean(StaticConfig.class);
        setAccount(staticConfig.getAccount());
        setPassword(staticConfig.getPassword());
        Map map = new HashMap();
        map.put("account",account);//API账号
        map.put("password",password);//API密码
        map.put("msg","【XXX】您好,您的验证码是{"+msg+"}");//短信内容
        map.put("phone",phone);//手机号
        map.put("report","true");//是否需要状态报告
        map.put("extend","123");//自定义扩展码
        JSONObject js = (JSONObject) JSONObject.toJSON(map);
        Map<String, Object> requestBody = JSONObject.parseObject(sendSmsByPost(SERVERURL, js.toString()));
        logger.info("创云短信接口返回的数据----------------");
        logger.info("{Code:" + requestBody.get("code")+",msgId:" + requestBody.get("msgId")+",time:"+
                requestBody.get("time")+",errorMsg:"+ requestBody.get("errorMsg")+"}");
        if(requestBody.get("code").equals("0")){//发送成功
            return true;
        }else{
            return false;
        }

    }

    /***
     *
     * @param path   路径
     * @param postContent 短信参数
     * @return
     */
    public static String sendSmsByPost(String path, String postContent) {
        URL url = null;
        try {
            url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setConnectTimeout(10000);
            httpURLConnection.setReadTimeout(10000);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.connect();
            OutputStream os=httpURLConnection.getOutputStream();
            os.write(postContent.getBytes("UTF-8"));
            os.flush();
            StringBuilder sb = new StringBuilder();
            int httpRspCode = httpURLConnection.getResponseCode();
            if (httpRspCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}

接口访问即可
2022-08-30 11:23:34.259 [http-nio-8086-exec-1] INFO org.jeecg.common.sms.DmSmsHelper:65 - 创云短信接口返回的数据----------------
2022-08-30 11:23:34.260 [http-nio-8086-exec-1] INFO org.jeecg.common.sms.DmSmsHelper:66 - {Code:0,msgId:22083011233400202212000006309352,time:20220830112334,errorMsg:}
2022-08-30 11:25:22.112 [http-nio-8086-exec-4] INFO org.jeecg.common.sms.DmSmsHelper:65 - 创云短信接口返回的数据----------------
2022-08-30 11:25:22.113 [http-nio-8086-exec-4] INFO org.jeecg.common.sms.DmSmsHelper:66 - {Code:107,msgId:,time:20220830112522,errorMsg:手机号码格式错误}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值