【Java】腾讯云发送短信验证码-Struts2

腾讯云有一个免费的套餐,注册之后每月就有100条免费的短信套餐,用来测试很方便。

appid,appkey,templateId,smsSign都需要获得面给套餐后申请。申请大概半小时可以搞定。

package com.hj.action;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import org.json.JSONException;
import java.io.IOException;

public class TelCodeAction {
    private String telephone;
    // 短信应用 SDK AppID
    private int appid = 140031241; // SDK AppID 以1400开头
    // 短信应用 SDK AppKey
    private String appkey = "aaaa";
    int templateId = 7839; // NOTE: 这里的模板 ID`7839`只是示例,真实的模板 ID 需要在短信控制台中申请
    // 签名
    String smsSign = "xx网站";

    public String execute(){
        // int code = (int) (Math.random()*8999+1000);
        int code = 3838438;
        String msg = "【xx网站】您的验证码为"+code+",在1分钟内有效。如非本人操作请忽略本短信。";
        System.out.println(msg);

        try {
            SmsSingleSender ssender = new SmsSingleSender(this.appid, this.appkey);
            SmsSingleSenderResult result = ssender.send(0, "86", telephone,
                    msg, "", "");
            System.out.println(result);
        } catch (HTTPException e) {
            // HTTP 响应码错误
            e.printStackTrace();
        } catch (JSONException e) {
            // JSON 解析错误
            e.printStackTrace();
        } catch (IOException e) {
            // 网络 IO 错误
            e.printStackTrace();
        }

        return "success";
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
}

猜你喜欢

转载自www.cnblogs.com/to-red/p/11314649.html