Java 云片验证码短信发送

本文详细介绍了如何使用云片网的API进行短信验证码的发送。从获取APIKEY到配置参数,再到Java代码实现,一步步指导如何在项目中集成短信服务。包括配置文件设置、Bean编写、控制器和实现类的代码示例。

####1.获取云片APIKEY
登录云片官网:www.yunpian.com 获取APIKEY

####2.查看API文档
官网首页 进入API文档页面
![短信分类.png](https://upload-images.jianshu.io/upload_images/1708646-e7a122b902af26ea.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

####3.java配置
配置文件中添加
```java
captcha:
      apikey: xxxxxx
      url: https://sms.yunpian.com/v2/sms/single_send.json
      text: 【XXX】亲爱的%s,您的验证码是%s。有效期为%s秒,请尽快验证
      time: 120
```

####4.编写bean,从配置文件中获取对应参数
```java
@Component
@ConfigurationProperties(prefix = "spring.captcha")
public class CaptchaConfig {
    private String apikey;
    private String url;
    private String text;
    private String time;

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getApikey() {
        return apikey;
    }

    public void setApikey(String apikey) {
        this.apikey = apikey;
    }
}
```

####5.控制类
```java
@RestController
@RequestMapping("api")
@Api(value = "Message-Api", description = "短信发送相关API")
public class CaptchaRestController {
    @Autowired
    private SmsService smsService;
    @Autowired
    private CaptchaConfig captchaConfig;

    /**
     * 发送短信验证码
     *
     * @param request 请求参数
     */
    @RequestMapping(value = "/verification/get", method = RequestMethod.POST)
    @ApiOperation(notes = "发送短信验证码", httpMethod = "POST", value = "发送短信验证码")
    public Response<HashMap> sendCaptchaMessage(@RequestBody Request<CaptchaGetParam> request) {
        CaptchaGetParam param = request.getParam();
        Response<HashMap> response = new Response<>();
        String mobile = param.getPhone();
        if(!ValidatorUtil.validatorPhone(mobile)){
            response.setResult(ConstantDef.RESPONSE.FAIL);
            response.setMessage("请输入正确的号码!");
            response.setData(new HashMap());
            return response;
        }
        String captcha = SmsService.createRandom(Boolean.TRUE, 6);
        try {
            return smsService.sendCaptchaMessage(mobile, captcha);
        } catch (IOException e) {
            response.setResult(ConstantDef.RESPONSE.FAIL);
            response.setMessage("验证码发送失败!");
            response.setData(new HashMap());
            return response;
        }

    }
}
```

####6.实现类
```java
@Service
public class SmsService {
    private static Logger logger = LoggerFactory.getLogger(SmsService.class);
    @Autowired
    private CaptchaConfig captchaConfig;

    public Response<HashMap> sendCaptchaMessage(String phone, String captcha) throws IOException {
        Response<HashMap> response = new Response<>();
        String message = String.format(captchaConfig.getText(), "用户", captcha, captchaConfig.getTime());
        HttpClient httpclient = new HttpClient();
        PostMethod post = new PostMethod(captchaConfig.getUrl());
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        post.addParameter("apikey", captchaConfig.getApikey());
        post.addParameter("text", message);
        post.addParameter("mobile", phone);
        int status = httpclient.executeMethod(post);
        String info = new String(post.getResponseBody(), "UTF-8");
        logger.debug(info);
        if(status == 200){
            CacheManager.getInstance().putListener().put(phone, captcha, Long.parseLong(captchaConfig.getTime()));
            response.setResult(ConstantDef.RESPONSE.SUCCESS);
            response.setMessage("验证码发送成功!");
            response.setData(new HashMap());
            return response;
        }else {
            JSONObject jsonObject= JSON.parseObject(info);
            response.setResult(ConstantDef.RESPONSE.FAIL);
            response.setMessage((String) jsonObject.get("detail"));
            response.setData(new HashMap());
            return response;
        }

    }


    /**
     * 创建指定数量的随机字符串
     *
     * @param numberFlag 是否是数字
     * @param length
     * @return
     */
    public static String createRandom(boolean numberFlag, int length) {
        String retStr = "";
        String strTable = numberFlag ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < length; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
                bDone = false;
            }
        } while (bDone);

        return retStr;
    }
}
```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值