一.开通短信服务

  • 本来想整合阿里云短信服务的,可是签名一直审核不过,所以在阿里云的云市场找到了一个替代产品(sddx)

  • 接下来小伙伴们按照自己的经济实力购买或者用免费的5条(我就是用免费的5条了)

  • 购买完了以后在右上角自己的订单中查看自己的appcode

二.整合步骤

1.创建一个项目

  • 这里我就创建一个简单的maven项目的了

2.导入相关依赖

<!--山东鼎信短信依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3.3</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-util</artifactId>
<version>9.3.7.v20160115</version>
</dependency>

3.直接复制下面的工具类HttpUtils

package com.qbb.yygh.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; /**
* @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
* @version 1.0
* @date 2022-03-27 4:22
* @Description:发送手机验证码的HttpClient工具类
*/
public class HttpUtils { /**
* get
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doGet(String host, String path, String method, Map<String, String> headers,
Map<String, String> querys) throws Exception {
HttpClient httpClient = wrapClient(host); HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
} return httpClient.execute(request);
} /**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers,
Map<String, String> querys, Map<String, String> bodys) throws Exception {
HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
} if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(); for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
} return httpClient.execute(request);
} /**
* Post String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers,
Map<String, String> querys, String body) throws Exception {
HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
} if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
} return httpClient.execute(request);
} /**
* Post stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers,
Map<String, String> querys, byte[] body) throws Exception {
HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
} if (body != null) {
request.setEntity(new ByteArrayEntity(body));
} return httpClient.execute(request);
} /**
* Put String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers,
Map<String, String> querys, String body) throws Exception {
HttpClient httpClient = wrapClient(host); HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
} if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
} return httpClient.execute(request);
} /**
* Put stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers,
Map<String, String> querys, byte[] body) throws Exception {
HttpClient httpClient = wrapClient(host); HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
} if (body != null) {
request.setEntity(new ByteArrayEntity(body));
} return httpClient.execute(request);
} /**
* Delete
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path, String method, Map<String, String> headers,
Map<String, String> querys) throws Exception {
HttpClient httpClient = wrapClient(host); HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
} return httpClient.execute(request);
} private static String buildUrl(String host, String path, Map<String, String> querys)
throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
} return sbUrl.toString();
} private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
} return httpClient;
} private static void sslClient(HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
} public void checkClientTrusted(X509Certificate[] xcs, String str) { } public void checkServerTrusted(X509Certificate[] xcs, String str) { }
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
}

4.复制发送验证码的工具类SMSUtils

package com.qbb.yygh.utils;

import org.apache.http.HttpResponse;

import java.util.HashMap;
import java.util.Map; /**
* @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
* @version 1.0
* @date 2022-04-23 21:12
* @Description:
*/
public class SMSUtils { /**
* 发送短信
*
* @param phoneNumbers 手机号码
* @param param 4位或6位数字的验证码
* @throws Exception
*/
public static void sendShortMessage(String phoneNumbers, String param) throws Exception {
String host = "http://dingxin.market.alicloudapi.com";
String path = "/dx/sendSms";
String method = "POST";
String appcode = "你自己的appcode";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE xxxxxxxxx
headers.put("Authorization", "APPCODE " + appcode);
Map<String, String> querys = new HashMap<String, String>();
querys.put("mobile", phoneNumbers);
querys.put("param", "code:" + param);
querys.put("tpl_id", "TP1711063");
Map<String, String> bodys = new HashMap<String, String>(); try {
/**
* 重要提示如下:
* HttpUtils请从
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
* 下载
*
* 相应的依赖请参照
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
*/
HttpResponse httpResponse = HttpUtils.doPost(host, path, method, headers, querys, bodys);
System.out.println(httpResponse.toString());
//获取response的body
//System.out.println(EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
e.printStackTrace();
}
}
}

5.生成4|6为随机验证码工具类

package com.qbb.yygh.utils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random; /**
* @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
* @version 1.0
* @date 2022-03-27 4:22
* @Description:生成四位和六位的随机数字
*/
public class RandomUtils { 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;
}
}

6.写个测试类测试一下

 try {
// 生成4位数验证码
String randomCode = RandomUtils.getFourBitRandom();
// 将验证码存入redis中
redisTemplate.opsForValue().set(key, randomCode, 10L, TimeUnit.DAYS);
// 发送验证码
// SMSUtils.sendShortMessage(phone, randomCode);
return 1;
} catch (Exception e) {
throw new YyghException("短信发送失败", -1);
}

整合成功

Java项目整合短信验证码的更多相关文章

  1. java实现发送短信验证码

    java实现短信验证码发送 由于我们使用第三方平台进行验证码的发送,所以首先,我们要在一个平台进行注册. 在这里我选择是秒嘀科技,因为新人注册会赠送十元,足够测试使用了. 注册完成后,我们需要获取自己 ...

  2. Java 生成六位短信验证码

    在<Java 生成三位随机数>中,简要介绍了使用Java生成三位随机数的方法,前几天在工作中遇到生成6位短信验证码的需求,验证码由6位随机数字构成,不包含字母.6位随机数通常用作短信验证码 ...

  3. SpringSceurity(4)---短信验证码功能实现

    SpringSceurity(4)---短信验证码功能实现 有关SpringSceurity系列之前有写文章 1.SpringSecurity(1)---认证+授权代码实现 2.SpringSecur ...

  4. java实现注册的短信验证码

    最近在做只能净化器的后台用户管理系统,需要使用手机号进行注册,找了许久才大致了解了手机验证码实现流程,今天在此和大家分享一下. 我们使用的是榛子云短信平台, 官网地址:http://smsow.zhe ...

  5. java + maven 实现发送短信验证码功能

    如何使用java + maven的项目环境发送短信验证码,本文使用的是榛子云短信 的接口. 1. 安装sdk 下载地址: http://smsow.zhenzikj.com/doc/sdk.html ...

  6. java 阿里云接口实现发送短信验证码

    此刻自己做的小项目中,需要用到手机发送短信验证码实现注册功能,于是就去阿里云注册了账号,并实现随机发送验证码的功能 第一步:在阿里云官网登录注册   已有支付宝或淘宝的账号可以直接登录,最后需要实名认 ...

  7. 阿里云短信服务发送短信验证码(JAVA开发此功能)

    开发此功能需注册阿里云账号,并开通短信服务(免费开通) 充值后,不会影响业务的正常使用!(因为发送验证类短信:1-10万范围的短信是0.045元/条).开发测试使用,充2块钱测试足够了 可参考阿里云官 ...

  8. Java调用WebService接口实现发送手机短信验证码功能,java 手机验证码,WebService接口调用

    近来由于项目需要,需要用到手机短信验证码的功能,其中最主要的是用到了第三方提供的短信平台接口WebService客户端接口,下面我把我在项目中用到的记录一下,以便给大家提供个思路,由于本人的文采有限, ...

  9. java发送短信验证码的功能实现

    总结一下发送短信验证码的功能实现 (题外话:LZ是在腾讯云买的第三方(山东鼎信)短信服务平台的接口,1块钱20次的套餐来练手,哈哈,给他们打个广告,有需要的可以去购买哈,下面是购买链接短信服务平台购买 ...

  10. thinkphp整合系列之短信验证码、订单通知

    现在这个短信通知泛滥的年代:应用如果没有个短信注册:你都不敢说你是搞开发的: 这个验证码搞起来是不难的:但是如果刚接触也是有点不知从哪下手的迷茫: 先讲下概念: 要想发送验证码:需要至少三项:appi ...

随机推荐

  1. 《SQL与数据库基础》08. 多表查询

    目录 多表查询 多表关系 一对多 多对多 一对一 多表查询概述 分类 内连接 外连接 自连接 联合查询 子查询 分类 标量子查询 列子查询 行子查询 表子查询 案例 本文以 MySQL 为例 多表查询 ...

  2. legend的用法

    常规使用legend的方法 1. 自动检测 设置title的label标签,随后使用不带参数的legend函数也会自动显示(但不限于一种方式设置图形的label,只要设置了图形的label,使用leg ...

  3. [htmlayout] picture标签替代img, 解决更新图片数据后依然显示原图片数据

    在hl中, 你可能遇到过这样的情况.   给img标签设置了一个图片路径.   在软件使用过程中对这个路径的数据进行过重写, 删除等等 但img依然还是显示最初载入的图片数据. 解决办法: 用&quo ...

  4. C++算法之旅、06 基础篇 | 第四章 动态规划 详解

    常见问题 闫式DP分析法 状态表示 集合 满足一定条件的所有方案 属性 集合(所有方案)的某种属性(Max.Min.Count等) 状态计算(集合划分) 如何将当前集合划分成多个子集合 状态计算相当于 ...

  5. 基于react18+vite4+arco.design搭建极简版后台管理模板

    趁着国庆前夕整了一个vite4结合react18搭建后台管理模板,搭配上字节团队react组件库ArcoDesign,整体操作功能非常丝滑.目前功能支持多种模板布局.暗黑/亮色模式.国际化.权限验证. ...

  6. OpenJDK17-JVM源码阅读-ZGC-并发标记

    1.ZGC简介 1.1 介绍 ZGC 是一款低延迟的垃圾回收器,是 Java 垃圾收集技术的最前沿,理解了 ZGC,那么便可以说理解了 java 最前沿的垃圾收集技术. 从 JDK11 中作为试验特性 ...

  7. Vue之style的用法

    Vue中style的用法总结如下: v-bind:style  简写:style 1.基本用法 <!DOCTYPE html> <html lang="en"&g ...

  8. Linux账号密码安全运维

    前言 随着云计算厂商的兴起,云资源如ECS不再只有企业或者公司才会使用,普通人也可以自己买一台ECS来搭建自己的应用或者网站.虽然云计算厂商帮我们做了很多安全相关的工作,但并不代表我们的机器资源就绝对 ...

  9. [Python急救站课程]叠加等边三角形的绘制

    叠加等边三角形的绘制 from turtle import * penup() fd(-100) pendown() pensize(10) seth(60) fd(200) seth(-60) fd ...

  10. 如何正确执行 DORA 指标

    DevOps 研究与 DORA 评估指标可帮助我们深入了解软件开发和交付流程的性能和效率.这些指标包括部署频率.变更交付时间.变更失败率和平均恢复时间等方面.DORA 指标对于管理开发团队(从团队领导 ...