2024/06/09

news/2024/10/8 0:29:16

学习时长:4.5小时

代码行数:121行

博客数量:1篇

今日主要学习了调用阿里云api来完成发送短信验证码

首先要在阿里云开通短信服务

然后申请资质,创建模板。

 

然后使用api使用

 

然后就会生成对应的sdk示例

// This file is auto-generated, don't edit it. Thanks.
package demo;import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.core.http.HttpClient;
import com.aliyun.core.http.HttpMethod;
import com.aliyun.core.http.ProxyOptions;
import com.aliyun.httpcomponent.httpclient.ApacheAsyncHttpClientBuilder;
import com.aliyun.sdk.service.dysmsapi20170525.models.*;
import com.aliyun.sdk.service.dysmsapi20170525.*;
import com.google.gson.Gson;
import darabonba.core.RequestConfiguration;
import darabonba.core.client.ClientOverrideConfiguration;
import darabonba.core.utils.CommonUtil;
import darabonba.core.TeaPair;//import javax.net.ssl.KeyManager;
//import javax.net.ssl.X509TrustManager;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.io.*;public class SendSms {public static void main(String[] args) throws Exception {// HttpClient Configuration/*HttpClient httpClient = new ApacheAsyncHttpClientBuilder().connectionTimeout(Duration.ofSeconds(10)) // Set the connection timeout time, the default is 10 seconds.responseTimeout(Duration.ofSeconds(10)) // Set the response timeout time, the default is 20 seconds.maxConnections(128) // Set the connection pool size.maxIdleTimeOut(Duration.ofSeconds(50)) // Set the connection pool timeout, the default is 30 seconds// Configure the proxy.proxy(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("<your-proxy-hostname>", 9001)).setCredentials("<your-proxy-username>", "<your-proxy-password>"))// If it is an https connection, you need to configure the certificate, or ignore the certificate(.ignoreSSL(true)).x509TrustManagers(new X509TrustManager[]{}).keyManagers(new KeyManager[]{}).ignoreSSL(false).build();*/// Configure Credentials authentication information, including ak, secret, tokenStaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()// Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set..accessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")).accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))//.securityToken(System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN")) // use STS token
                .build());// Configure the ClientAsyncClient client = AsyncClient.builder().region("cn-beijing") // Region ID//.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)//.serviceConfiguration(Configuration.create()) // Service-level configuration// Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(ClientOverrideConfiguration.create()// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi.setEndpointOverride("dysmsapi.aliyuncs.com")//.setConnectTimeout(Duration.ofSeconds(30))
                ).build();// Parameter settings for API requestSendSmsRequest sendSmsRequest = SendSmsRequest.builder().signName("")//签名名称.templateCode("")//模板代码.phoneNumbers("")//电话.templateParam("{\"code\":\"1234\"}")// Request-level configuration rewrite, can set Http request parameters, etc.// .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();// Asynchronously get the return value of the API requestCompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);// Synchronously get the return value of the API requestSendSmsResponse resp = response.get();System.out.println(new Gson().toJson(resp));// Asynchronous processing of return values/*response.thenAccept(resp -> {System.out.println(new Gson().toJson(resp));}).exceptionally(throwable -> { // Handling exceptionsSystem.out.println(throwable.getMessage());return null;});*/// Finally, close the client
        client.close();}}

再参照短信服务_SDK中心-阿里云OpenAPI开发者门户 (aliyun.com)

完成自己的工具类

package com.share.viedo_app.util;import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.google.gson.Gson;public class AliMes {public boolean sendMes(String phone,String code){try {Config config=new Config().setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));System.out.println(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));config.endpoint = "dysmsapi.aliyuncs.com";Client client=new Client(config);SendSmsRequest request=new SendSmsRequest();request.phoneNumbers=phone;request.signName="";request.templateCode="";request.templateParam="{\"code\":\""+code+"\"}";SendSmsResponse response=client.sendSms(request);if(response.getBody().code!=null&&response.getBody().code.equals("OK")){return true;}else {return false;}}catch (Exception e){System.out.println(e);return false;}}
}

最后调用就收到发送短信了

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

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

相关文章

m基于PSO粒子群优化的LDPC码OMS译码算法最优偏移参数计算和误码率matlab仿真

1.算法仿真效果 matlab2022a仿真结果如下:2.算法涉及理论知识概要Offset Min-Sum(OMS)译码算法是LDPC码的一种低复杂度迭代解码方法,它通过引入偏移量来减轻最小和算法中的量化效应,从而提高解码性能。当应用粒子群优化(PSO)来计算OMS译码算法中的最优偏移参数时,目标是…

第五日

5. 最长回文子串 题目描述:给你一个字符串 s,找到 s 中最长的回文子串 思路从最长入手,用p[i][j]记录从i-j中的最长回文 从回文入手,抓住回文中的中间值,依次求解各个字符作为中间值时的情况,并比较找出最大尝试第一次尝试 class Solution:def longestPalindrome(self, s…

南昌航空大学软院第二次博客

一、前言 1.通过这几次PTA的大作业,加深了我对java编程的了解和熟练度。 这一段时间的学习:这一段时间主要训练了有关java接口和多态相关方面的知识,这部分内容是Java的重要组成部分,他们共同提高了代码的开发效率,使得代码设计灵活,维护简单,结构清晰 关于类的特性:在设…

基于WSN网络的定向步幻影路由算法matlab仿真

1.程序功能描述系统设计背景技术介绍与现状简介:现在是信息爆炸的一个时代,因此对于个人的隐私以及信息的隐私保护都应该被实时重视着的问题;无线传感器网络其所采用的无线多跳通信方式易收到攻击者的攻击,引发严重的位置隐私泄露问题。在本课题中,我们将对比NDRW路由和定…

音频信号处理入门

普及知识 什么是信号分析? 将一个复杂信号分解成若干简单信号分量之和,或者用有限的一组参量去表示一个复杂波形的信号,从这些简单的分量组成情况去考察复杂信号的特性。 对信号分析的过程实际上就是一个特征提取的过程,从一段复杂的波形中提取我们需要的信息。 为什么要分…

7-1大作业集训总结心得

第二轮大作业比起第一轮大作业难度上升了不少,运用到的东西更新,更先进,所涉及的思维设计,逻辑框架也更难,还有其计算的设计也会很复杂很难。 第二轮大作业的第一次作业难度低,简单类型,因为其信息输入每一行固定的就是两个设备,都可以不用正则表达式光用split就能写出…

A successful Git branching model

A successful Git branching model https://nvie.com/posts/a-successful-git-branching-model/The main branches Supporting branches Feature branches Release branches Hotfix branches 出处:http://www.cnblogs.com/lightsong/本文版权归作者和博客园共有,欢迎转载,但…

第二次博客(PTA四到六次大作业)

第四次作业:7-4 答题判题程序-4 分数 87 作者 蔡轲 单位 南昌航空大学 设计实现答题程序,模拟一个小型的测试,要求输入题目信息、试卷信息、答题信息、学生信息、删除题目信息,根据输入题目信息中的标准答案判断答题的结果。本题在答题判题程序-3基础上新增的内容统一附加在…