谷粒商城实战笔记-213-商城业务-认证服务-整合短信验证码服务

news2024/9/19 10:44:25

文章目录

  • 一,开通阿里云云市场短信服务
    • 1,阿里云开通免费短信服务并调试
    • 2,整合短信服务
      • 2.1 下载HttpUtils代码
      • 2.2 开发调用短信服务的组件
      • 2.3 测试
  • HttpUtils代码

这一节主要内容是整合短信发送服务。

一,开通阿里云云市场短信服务

1,阿里云开通免费短信服务并调试

登录阿里云后,切换到云市场,搜索栏中输入短信,会列出很多短信服务,选择可以免费使用的短信服务,如下。

在这里插入图片描述

以第一个短信服务为例,点击进入服务界面,可以看到有个免费使用的按钮,点击免费使用,开通免费使用功能,点击前往控制台进入控制台。

在这里插入图片描述

进入控制台后可以看到AppKey、AppSercret、AppCode,后续在调用短信服务接口时,用这些信息进行身份验证。
在这里插入图片描述
此外,还可以在控制台调试接口。

在这里插入图片描述
点击调试,进入调试界面,输入手机号码,点击发起请求,即可发送短信。

在这里插入图片描述
界面右侧会显示请求结果。

在这里插入图片描述

2,整合短信服务

在短信服务的控制台,点击接口,进入整合文档。

在这里插入图片描述

在新的界面,选择请求示例,查看Java示例。

在这里插入图片描述

2.1 下载HttpUtils代码

在实例中用到了HttpUtils,代码来自https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java,在第三方服务模块中创建这个类。

在这里插入图片描述

2.2 开发调用短信服务的组件

因为调用短信服务需要使用AppCode,所以不能直接在前端调用短信服务,必须通过后台转发,否则会保留这个关键信息。

component包下创建SmsComponent类,发送短信的代码直接copy控制台的实例代码接口。

package com.atguigu.gulimall.thirdparty.component;

import cn.hutool.core.util.StrUtil;
import com.atguigu.gulimall.thirdparty.util.HttpUtils;
import lombok.Data;
import org.apache.http.HttpResponse;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


@ConfigurationProperties(prefix = "spring.cloud.alicloud.sms")
@Data
@Component
public class SmsComponent {

    private String host;
    private String path;
    private String smsSignId;
    private String templateId;
    private String appcode;

    public void sendCode(String phone,String code) {
        String host = this.host;
        String path = this.path;
        String method = "POST";
        String appcode = this.appcode;
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone);
        querys.put("param", StrUtil.format("**code**:{},**minute**:5", code));

        //smsSignId(短信前缀)和templateId(短信模板),可登录国阳云控制台自助申请。
        // 参考文档:http://help.guoyangyun.com/Problem/Qm.html
        querys.put("smsSignId", this.smsSignId);
        querys.put("templateId", this.templateId);
        Map<String, String> bodys = new HashMap<String, String>();


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从\r\n\t    \t* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java\r\n\t    \t* 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

为了规范,关键的参数要配置到配置文件中。

spring:
  cloud:
    alicloud:
      sms:
        host: https://gyytz.market.alicloudapi.com
        path: /sms/smsSend
        smsSignId: 2e65b1bb3d05c9d125465e2
        templateId: 908e946c876d13f084ad
        appcode: aa1eb5722c4fc35

通过注解@ConfigurationProperties(prefix = "spring.cloud.alicloud.sms")将配置注入到对象中。

注意还要引入依赖。

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>

2.3 测试

编写单元测试,给自己的手机发送短信。

在这里插入图片描述

	@Autowired
    private SmsComponent smsComponent;

    @Test
    public void testSms() {
        smsComponent.sendCode("180****9051", "888888");
    }

单元测试通过且手机收到短信,说明整合短信服务成功。

HttpUtils代码

package com.atguigu.gulimall.thirdparty.util;


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;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

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;

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);
        }
    }
}

这是一个工具类,主要作用是提供对HTTP请求的封装和简化操作。

以下是该类的主要功能点:

  1. 支持HTTP请求:类中定义了多种HTTP请求方法,包括GET、POST、PUT和DELETE。
  2. 自定义请求头:允许用户为每个请求添加自定义的HTTP头。
  3. 支持查询参数:可以为GET和POST请求添加查询参数。
  4. 支持表单数据:对于POST请求,支持发送表单数据(application/x-www-form-urlencoded)。
  5. 支持字符串和流数据:POST和PUT请求可以发送字符串或字节流作为请求体。
  6. SSL支持:提供了对HTTPS请求的支持,包括对SSL证书的简单管理。
  7. URL构建:内部方法用于构建完整的请求URL,包括基础URL和查询参数。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2049399.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

多输入多输出 | Matlab实现CPO-BP冠豪猪优化算法优化BP神经网络多输入多输出预测

多输入多输出 | Matlab实现CPO-BP冠豪猪优化算法优化BP神经网络多输入多输出预测 目录 多输入多输出 | Matlab实现CPO-BP冠豪猪优化算法优化BP神经网络多输入多输出预测预测效果基本介绍程序设计往期精彩参考资料 预测效果 基本介绍 多输入多输出 | Matlab实现CPO-BP冠豪猪优化…

CUDA-MODE课程笔记 第6课: 如何优化PyTorch中的优化器

我的课程笔记&#xff0c;欢迎关注&#xff1a;https://github.com/BBuf/how-to-optim-algorithm-in-cuda/tree/master/cuda-mode CUDA-MODE课程笔记 第6课: 如何优化PyTorch中的优化器 课程内容 上面三张Slides讲述了运行时间&#xff08;runtime&#xff09;和内存使用&…

ChatGPT 3.5/4.0 新手使用手册(详细版)

1. 什么是 ChatGPT&#xff1f; ChatGPT是由 OpenAI 开发的先进人工智能语言模型&#xff0c;能够理解并生成自然语言文本。它可以帮助你进行写作、回答问题、提供建议&#xff0c;甚至参与对话。ChatGPT 3.5 和 4.0 是两个不同版本&#xff0c;它们都拥有强大的语言处理能力&…

sublime text 4 安装(含激活码)安装破解汉化 Sublime Text 4 的操作指南

sublime text 4 安装&#xff08;含激活码&#xff09; 一、下载步骤 官网地址&#xff1a;Sublime Text - the sophisticated text editor for code, markup and prosehttps://link.zhihu.com/?targethttps://www.sublimetext.com/ windows下载链接&#xff1a;Thank You -…

【数据结构算法经典题目刨析(c语言)】使用数组实现循环队列(图文详解)

&#x1f493; 博客主页&#xff1a;C-SDN花园GGbond ⏩ 文章专栏&#xff1a;数据结构经典题目刨析(c语言) 目录 一.题目描述 二.解题思路 1.循环队列的结构定义 2.队列初始化 3.判空 4.判满 5.入队列 6.出队列 7.取队首元素 8.取队尾元素 三.完整代码实…

【Datawhale AI夏令营第四期】魔搭-AIGC方向 Task03笔记 原神风格Lora尝试 ComfyUI Lora微调 补充选学内容

【Datawhale AI夏令营第四期】魔搭-AIGC方向 Task03笔记 原神风格Lora尝试 ComfyUI Lora微调 首先我们继续推进网课进度。 https://space.bilibili.com/1069874770 传送门 WorldArt锦书产品介绍&#xff1a; 我属实是没想到这个产品居然还可以用作遗迹鉴定和名家笔记仿写这样…

2.2算法的时间复杂度与空间复杂度——经典OJ

本博客的OJ标题均已插入超链接&#xff0c;点击可直接跳转~ 一、消失的数字 1、题目描述 数组nums包含从0到n的所有整数&#xff0c;但其中缺了一个。请编写代码找出那个缺失的整数。你有办法在O(n)时间内完成吗&#xff1f; 2、题目分析 &#xff08;1&#xff09;numsS…

Java流程控制之循环结构(附案例说明)超详细

循环结构&#xff1a;根据循环条件&#xff0c;重复性执行某段代码 for循环 while 循环 do-while 循环 凡是循环 就有4个要素&#xff1a; 1、初始化要素2、循环条件&#xff08;一定是boolean类型的变量或表达式&#xff09; 3、循环体 4、迭代部分 for 循环格式 for(1;2;…

阿里声音项目Qwen2-Audio的部署安装,在服务器Ubuntu22.04系统——点动科技

阿里声音项目Qwen2-Audio的部署安装&#xff0c;在服务器Ubuntu22.04系统——点动科技 一、ubuntu22.04基本环境配置1.1 更换清华Ubuntu镜像源1.2 更新包列表&#xff1a;2. 安装英伟达显卡驱动2.1 使用wget在命令行下载驱动包2.2 更新软件列表和安装必要软件、依赖2.2 卸载原有…

JAVA学习之知识补充(下)

六&#xff1a;File类与IO流&#xff1a; 这里给出三种常见的初始化方法&#xff1a; 通过文件路径初始化: File file new File("C:/example/test.txt");这种方法用于创建一个文件对象&#xff0c;该文件对象表示指定路径的文件或目录。例如&#xff1a;File fil…

Zookeeper服务注册及心跳机制详解

ZooKeeper提供了一种类似于文件目录的结构来保存key值&#xff0c;其提供了四种key类型&#xff0c;分别是持久节点&#xff0c;临时节点&#xff0c;持久有序节点&#xff0c;临时有序节点。其中临时节点的特性是当创建此节点的会话断开时&#xff0c;节点也会被删除。这一特性…

xss.function靶场(easy)

文章目录 第一关Ma Spaghet!第二关Jefff第三关Ugandan Knuckles第四关Ricardo Milos第五关Ah Thats Hawt第六关Ligma第七关Mafia第八关Ok, Boomer 网址&#xff1a;https://xss.pwnfunction.com/ 第一关Ma Spaghet! 源码 <!-- Challenge --> <h2 id"spaghet&qu…

一文掌握 Web 测试:功能、界面、兼容与安全的综合测试指南!

随着Web技术的不断演进&#xff0c;测试除了对应用的功能性、界面美观性、跨平台兼容性的基本要求外、安全性和性能的要求也逐步增高。因此&#xff0c;全面、系统的测试思维和策略成为了保证Web应用高质量的关键因素。本篇文章将从功能测试、界面测试、兼容性测试和安全测试四…

AI歌手-五月天(声音转换)

重磅推荐专栏: 《大模型AIGC》 《课程大纲》 《知识星球》 本专栏致力于探索和讨论当今最前沿的技术趋势和应用领域,包括但不限于ChatGPT和Stable Diffusion等。我们将深入研究大型模型的开发和应用,以及与之相关的人工智能生成内容(AIGC)技术。通过深入的技术解析和实践经…

JavaScript - 数组对象中实用好玩的reduce方法

JavaScript中reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行)&#xff0c;将其结果汇总为单个返回值。 语法&#xff1a; arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue]) 参数配置&#xff1a; 参数名描述cal…

系列:水果甜度个人手持设备检测-github等开源库和方案

系列:水果甜度个人手持设备检测 -- github等开源库和方案 概述 通常来说&#xff0c;年纪轻轻的我们一般都喜欢走捷径&#xff0c;对于智能设备和算法软件领域来说&#xff0c;GitHub应该算为数不多的的捷径之一。就算因为效果不好/知识产权/方向不同等原因不用&#xff0c;…

XML外部实体注入

1.DTD实体及引用 DTD(文档类型定义)是一种用于定义XML文档结构和元素约束的方法。它可以描述一个XML文档的元素、属性、实体、注释等&#xff0c;从而规定了文档的结构和语法规则。DTD 通常是一个单独的文件&#xff0c;可以被多个XML文档所共享。 而在DTD中&#xff0c;实体…

日志分析-Windows

目录 Windows事件日志场景 1&#xff08;问题 1&#xff09;&#xff1a;服务器管理员向管理层提出了大量关于 PowerShell 在环境中被阻止的投诉。管理层最终批准在环境中使用 PowerShell。查看哪些日志、监控哪些事件 ID 等。场景 2&#xff08;问题 2&#xff09;&#xff1a…

Ubuntu 24.04系统部署Zabbix7.0

1、Ubuntu 24.04系统 阿里云镜像下载地址&#xff1a; https://mirrors.aliyun.com/ubuntu-releases/noble/ubuntu-24.04-live-server-amd64.iso 如果不使用Ubuntu系统&#xff0c;自己可以在下图选择对应版本。安装操作差不多&#xff0c;就命令有差异。 2、Zabbix版本 &am…

AVL树的学习

1.1 AVL树的概念 二叉搜索树虽可以缩短查找的效率&#xff0c;但如果数据有序或接近有序二叉搜索树将退化为单支树&#xff0c;查 找元素相当于在顺序表中搜索元素&#xff0c;效率低下。因此&#xff0c;两位俄罗斯的数学家G.M.Adelson-Velskii 和E.M.Landis在1962年 发明了…