一.开通短信服务

  • 本来想整合阿里云短信服务的,可是签名一直审核不过,所以在阿里云的云市场找到了一个替代产品(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. 银河麒麟SP2 auditd服务内存泄露问题

    这几天遇到基于海光服务器的银河麒麟V10 SP2版本操作系统出现内存无故增长问题. 排查发现auditd服务,占用了大量内存. 我的环境是银河麒麟V10 SP2 524,audit版本audit-3. ...

  2. 简单的Oracle增删改查笔记

  3. c语言代码练习14

    //设计一个猜数字游戏,需要提示猜大了还是小了,直到猜对为止 #define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include & ...

  4. go defer简介

    思考 开始之前,先考虑下下面的代码的执行结果: package main import "fmt" func test() int { i := 0 defer func() { ...

  5. 我试图扯掉这条 SQL 的底裤。

    你好呀,我是歪歪. 这次带大家盘一个我觉得有点意思的东西,也是之前写<一个烂分页,踩了三个坑!>这篇文章时,遇到的一个神奇的现象,但是当时忙着做文章搞定这个主线任务,就没有去深究这个支线任 ...

  6. GPL协议原文及中文翻译

    GPL协议原文及中文翻译 原文参考链接 翻译参考链接 原文 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 19 ...

  7. 生成CSR和自签名证书

    CSR,全称Certificate Signing Request(证书签发请求),是一种包含了公钥和与主题(通常是实体的信息,如个人或组织)相关的其他信息的数据结构.CSR通常用于向证书颁发机构(C ...

  8. 为zabbix穿上一件漂亮的外衣

    zabbix+Grafana 7.0  zabbix的环境已部署好的情况下,zabbix部分-- 略 Grafana简介: 1.Grafana自身并存储数据,数据从其它地方获取.需要配置数据源 2.G ...

  9. c#中原型模式详解

    基础介绍:   具体可分为2个角色:     Prototype(原型类):声明一个Clone自身的接口:     ConcretePrototype(具体原型类):,实现一个Clone自身的操作. ...

  10. ruoyi框架里面设置登录超时时间不能生效

    问题 项目使用到了ruoyi框架,给登录超时限制了12小时,但是每次几个小时后就提示过期,要求再登录一次. 首先怀疑是不是redis内存淘汰策略出现了问题. 先使用一下的命令 systemctl st ...