java发送短信验证码
时间: 2023-10-26 09:08:17 浏览: 169
要发送短信验证码,你需要使用短信服务提供商的 API。以下是一个使用阿里云短信服务的示例代码:
```java
import java.util.Random;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sms.model.v20170605.SendSmsRequest;
import com.aliyuncs.sms.model.v20170605.SendSmsResponse;
public class SmsSender {
private static final String ACCESS_KEY_ID = "your_access_key_id";
private static final String ACCESS_KEY_SECRET = "your_access_key_secret";
private static final String SIGN_NAME = "your_sign_name";
private static final String TEMPLATE_CODE = "your_template_code";
public static void sendSms(String phone) throws ClientException {
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", ACCESS_KEY_ID, ACCESS_KEY_SECRET);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Sms", "sms.aliyuncs.com");
IAcsClient client = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest();
request.setPhoneNumbers(phone);
request.setSignName(SIGN_NAME);
request.setTemplateCode(TEMPLATE_CODE);
String code = String.format("%04d", new Random().nextInt(10000));
request.setTemplateParam("{\"code\":\"" + code + "\"}");
SendSmsResponse response = client.getAcsResponse(request);
System.out.println("短信发送结果:" + response.getCode());
}
}
```
在上面的代码中,你需要替换以下常量:
- `your_access_key_id`:你的阿里云 Access Key ID
- `your_access_key_secret`:你的阿里云 Access Key Secret
- `your_sign_name`:你在阿里云短信服务中设置的签名名称
- `your_template_code`:你在阿里云短信服务中设置的短信模板编号
使用时,你只需要调用 `sendSms` 方法并传入要发送的手机号码即可。该方法会生成一个 4 位的随机验证码并发送到指定的手机号码上。
阅读全文