1.配置pom.xml
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.1.270</version><!-- 注:这里只是示例版本号(可直接使用),可获取并替换为 最新的版本号,注意不要使用4.0.x版本(非最新版本) -->
</dependency>
2.随机生成二维码类
package com.carolin_violet.travel_system.utils;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
/**
* 获取随机数
*
*/
public class RandomUtil {
private static final Random random = new Random();
private static final DecimalFormat fourdf = new DecimalFormat("0000");
private static final DecimalFormat sixdf = new DecimalFormat("000000");
public static String getFourBitRandom() {
return fourdf.format(random.nextInt(10000));
}
public static String getSixBitRandom() {
return sixdf.format(random.nextInt(1000000));
}
/**
* 给定数组,抽取n个数据
* @param list
* @param n
* @return
*/
public static ArrayList getRandom(List list, int n) {
Random random = new Random();
HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
// 生成随机数字并存入HashMap
for (int i = 0; i < list.size(); i++) {
int number = random.nextInt(100) + 1;
hashMap.put(number, i);
}
// 从HashMap导入数组
Object[] robjs = hashMap.values().toArray();
ArrayList r = new ArrayList();
// 遍历数组并打印数据
for (int i = 0; i < n; i++) {
r.add(list.get((int) robjs[i]));
System.out.print(list.get((int) robjs[i]) + "\t");
}
System.out.print("\n");
return r;
}
}
3. 使用官方的示例api稍微修改下
// code为自己随机生成的二维码,phone为需要发送验证码的手机号
@Override
public boolean send(String code, String phone) {
try {
Credential cred = new Credential("{腾讯云访问密钥id}", "{腾讯云访问密钥密码}");
HttpProfile httpProfile = new HttpProfile();
httpProfile.setReqMethod("GET");
httpProfile.setEndpoint("sms.tencentcloudapi.com");
ClientProfile clientProfile = new ClientProfile();
SmsClient client = new SmsClient(cred, "ap-nanjing",clientProfile);
SendSmsRequest req = new SendSmsRequest();
String sdkAppId = "1400679413";
req.setSmsSdkAppId(sdkAppId);
String signName = "{短信服务模板签名}";
req.setSignName(signName);
String templateId = "{短信服务模板id}";
req.setTemplateId(templateId);
String[] templateParamSet = {code};
req.setTemplateParamSet(templateParamSet);
String[] phoneNumberSet = {phone};
req.setPhoneNumberSet(phoneNumberSet);
SendSmsResponse res = client.SendSms(req);
System.out.println(SendSmsResponse.toJsonString(res));
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Q.E.D.