java如何实现手机验证码
实现手机验证码功能
生成随机验证码
使用Java的Random类或SecureRandom类生成随机数字验证码,通常为4-6位数字。
import java.util.Random;
public class VerificationCodeGenerator {
public static String generateCode(int length) {
Random random = new Random();
StringBuilder code = new StringBuilder();
for (int i = 0; i < length; i++) {
code.append(random.nextInt(10));
}
return code.toString();
}
}
存储验证码
将生成的验证码与手机号关联存储,可使用缓存如Redis,设置合理的过期时间(如5分钟)。
import redis.clients.jedis.Jedis;
public class CodeStorage {
private static final int EXPIRE_TIME = 300; // 5分钟
public static void storeCode(String phone, String code) {
try (Jedis jedis = new Jedis("localhost")) {
jedis.setex(phone, EXPIRE_TIME, code);
}
}
}
发送短信验证码
集成短信服务商API(如阿里云、腾讯云短信服务),通过HTTP请求发送验证码短信。
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class SmsSender {
public static void sendSms(String phone, String code) {
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpPost post = new HttpPost("https://sms.api.url");
post.setHeader("Content-Type", "application/json");
String json = String.format("{\"phone\":\"%s\",\"code\":\"%s\"}", phone, code);
post.setEntity(new StringEntity(json));
HttpResponse response = client.execute(post);
// 处理响应结果
} catch (Exception e) {
e.printStackTrace();
}
}
}
验证码校验
用户提交验证码后,从缓存中取出存储的验证码进行比对。
import redis.clients.jedis.Jedis;
public class CodeVerifier {
public static boolean verifyCode(String phone, String inputCode) {
try (Jedis jedis = new Jedis("localhost")) {
String storedCode = jedis.get(phone);
return inputCode != null && inputCode.equals(storedCode);
}
}
}
完整流程示例
将以上组件整合实现完整验证码流程。

public class SmsVerificationService {
public void sendVerificationCode(String phone) {
String code = VerificationCodeGenerator.generateCode(6);
CodeStorage.storeCode(phone, code);
SmsSender.sendSms(phone, code);
}
public boolean verify(String phone, String code) {
return CodeVerifier.verifyCode(phone, code);
}
}
注意事项
- 验证码有效期不宜过长,通常5-10分钟
- 同一手机号发送频率需限制,防止短信轰炸
- 生产环境建议使用线程安全的缓存方案
- 短信接口需要处理网络异常和重试机制
- 敏感信息如手机号需进行脱敏处理






