云片网短信服务使用Java
发送验证码
代码如下
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import java.util.Map;
import java.util.Random;
/**
* @Author ONE_LLX
* @Description //TODO
* @Date 13:51 2019/3/27
* @Class SmsUtils
* @Version v1.0
*导包
* <dependency>
* <groupId>com.yunpian.sdk</groupId>
* <artifactId>yunpian-java-sdk</artifactId>
* <version>1.2.7</version>
* </dependency>
**/
public class SmsUtils {
private final static String YUNPIAN_APIKEY="yunpian_apikey"; //key
private final static String REGISTINFO="registinfo";//模板信息
private final static int RANDOMSIZE=6; //验证码长度
/**
* 云片网发送手机验证码
* @param mobile 手机号码
* @return 成功的话返回验证码,失败的话返回 error字符串
*/
public static String sendSMS(String mobile){
//初始化clnt,使用单例方式
YunpianClient clnt = new YunpianClient(YUNPIAN_APIKEY).init();
String verifyCode = createRandomBySize(RANDOMSIZE);//生成短信验证码
//发送短信API
Map<String, String> param = clnt.newParam(2);
param.put(YunpianClient.MOBILE, mobile);
param.put(YunpianClient.TEXT, REGISTINFO+verifyCode);
Result<SmsSingleSend> r = clnt.sms().single_send(param);
clnt.close();
if (r.getCode()!=0){
return "error";
}
return verifyCode;
}
/**
* 根据size长度生成随机数字字符串
* @param size 长度
* @return
*/
public static String createRandomBySize(int size){
if (size<=0){
size=1;
}
int bound=1;
for (int i=1;i<size;i++){
bound=bound*10;
}
String verifyCode = String
.valueOf(new Random().nextInt((bound*10)-(bound+1)) + bound);//生成短信验证码
return verifyCode;
}
}