(最新)Java接入阿里云发送短信完整代码,附SDK下载

分类:Java开发 阅读(1)    2026年04月05日
本文介绍Java接入阿里云短信的功能,并提供相应的代码示例和SDK下载。

一、注册短信服务

阿里云短信服务: https://www.aliyun.com/product/sms

注册一个账号、申请资质签名模板。

二、Java SDK下载

SDK下载:阿里云短信SDK

Apache Maven安装SDK配置:

<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>dysmsapi20170525</artifactId>
  <version>4.5.0</version>
</dependency>

三、Java对接短信API

以下代码详细介绍了阿里云Java SDK 的使用步骤,仅作步骤示范。示例展示了如何调用 SendSms API 进行发送短信请求

完整示例代码:

package com.aliyun.sample;

import com.aliyun.tea.*;

public class Sample {

    /**
     * <b>description</b> :
     * <p>使用凭据初始化账号 Client</p>
     * @return Client
     * 
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        // 工程代码建议使用更安全的无 AK 方式,凭据配置方式请参见:https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client();
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setCredential(credential);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        
        com.aliyun.dysmsapi20170525.Client client = Sample.createClient();
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setPhoneNumbers("your_value")
                .setSignName("your_value");
        try {
            com.aliyun.dysmsapi20170525.models.SendSmsResponse resp = client.sendSmsWithOptions(sendSmsRequest, new com.aliyun.teautil.models.RuntimeOptions());
            System.out.println(new com.google.gson.Gson().toJson(resp));
        } catch (TeaException error) {
            // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
        }        
    }
}


标签: Java

本文链接:https://befun.ink/detail/20130.html
声明:本站信息原创或由互联网收集,未用于商业用途,如若侵权,请联系站长删除!