文章目录

  • 概要
  • 流程
  • 代码
  • 小结


概要

使用阿里短信实现Java手机短信验证,实测有效!!!

流程

准备工作:

登录阿里云 链接如下:https://www.aliyun.com/

进入控制台

设置Access Key

java 前端获取img 验证码 java获取短信验证码_java

 创建Access Key记住 Secret一会儿会用到,用到时查看Secret

java 前端获取img 验证码 java获取短信验证码_spring_02

在阿里云短信平台设置测试签名(因为自定义签名需要申请所以这儿就用专用的测试签名即可) 

https://dysms.console.aliyun.com/quickstart

java 前端获取img 验证码 java获取短信验证码_spring boot_03

可以点击调试,看验证码能否发送成功

java 前端获取img 验证码 java获取短信验证码_spring_04

代码

以上准备工作结束,接下来用Java代码来调用接口 代码很简单如下:

创建一个spring项目,添加依赖:

<dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>alibabacloud-dysmsapi20170525</artifactId>
            <version>2.0.23</version>
        </dependency>

然后创建一个测试类: 

package com.liu.zfb.test;

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;

public class SendSms {
    public static void main(String[] args) throws Exception {

        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId("自己的accessKeyId")
                .accessKeySecret("自己的accessKeySecret")
                //.securityToken("<your-token>") // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("undefined") // 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()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        String s = runNumber();
        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers("手机号")
                .signName("阿里云短信测试").templateCode("自己的模板code").templateParam("{\"code\":\""+s+"\"}")
                // 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 request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse 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 exceptions
            System.out.println(throwable.getMessage());
            return null;
        });*/

        // Finally, close the client
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaacvvvvvv"+resp.getHeaders());

        client.close();
    }
//    生成随机的验证码
    public static String runNumber() {
        String str="0123456789";
        StringBuilder sb=new StringBuilder(4);
        for(int i=0;i<6;i++)
        {
            char ch=str.charAt(new Random().nextInt(str.length()));
            sb.append(ch);
        }
        System.out.println(sb.toString());
        String code = sb.toString();
        return code;
    }

}

以上就可以实现手机接收验证码了 ,实测有效!!!

小结

接收到验证码后可以进行相应的业务应用比如登录,注册,具体大家也可以看官方文档 链接如下:

https://next.api.aliyun.com/api-tools/sdk/Dysmsapi?versinotallow=2017-05-25&language=java-async-tea