- 发送短信验证码首先要在互亿无线短信平台去开通短信服务,地址"ihuyi.com"
- 一定要留好自己申请的API ID,API key和模板
- 参数说明:
- 代码示例:
pom导包<!-- 短信 --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.0</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency>
新建发送短信工具类
package com.mes.util; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import java.io.IOException; /** * <p> * 发送短信验证码 * </p> */ public class SendSmsUtil { private static final String URL = "http://106.ihuyi.com/webservice/sms.php?method=Submit"; //国内请求路径 private static final String APPID = "admin"; private static final String APIKEY = "admin123456"; /** * 发送短信 * * @param phone 手机号 * @param content 短信内容 */ public static String send(String phone, String content) { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(URL); client.getParams().setContentCharset("GBK"); method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=GBK"); //todo 他提交短信 NameValuePair[] data = { new NameValuePair("account", APPID), new NameValuePair("password", APIKEY), new NameValuePair("mobile", phone), new NameValuePair("content", content), new NameValuePair("sign", "胡碴熟男"), }; method.setRequestBody(data); try { client.executeMethod(method); String submitResult = method.getResponseBodyAsString(); Document doc = DocumentHelper.parseText(submitResult); Element root = doc.getRootElement(); String code = root.elementText("code"); String msg = root.elementText("msg"); String smsid = root.elementText("smsid"); System.out.println(msg); if ("2".equals(code)) { System.out.println("短信提交成功"); } return code; } catch (IOException | DocumentException e) { e.printStackTrace(); return e.getMessage(); } } }
例如当页面需要操作用户找回密码,通过发送短信验证码操作时 放如redis,验证码失效5分钟
@Override public ResultInfo<?> getLoginCode(String phone) { String code = SendSmsUtil.getCode(phone); redissonClient.getBucket(RedisConstant.PHONE + phone, new JsonJacksonCodec()).set(code, 5, TimeUnit.MINUTES); return ResultInfo.success(code, "success"); }
/** * 获取验证码 * * @param phone * @return */ public static String getCode(String phone) { int mobileCode = (int) ((Math.random() * 9 + 1) * 100000); String content = "您正在操作找回密码,验证码为" + mobileCode + ",请不要把验证码泄露给其他人。"; send(phone, content); return String.valueOf(mobileCode); }
Java实现手机发送短信验证码
于 2022-12-19 15:56:53 首次发布