Java实现短信发送业务

1、业务需求

发送短信功能是一个很普遍的需求,比如验证码,快递单号,通知信息一类。 而在Java中实现短信功能相对简单,只需要调用短信服务商提供的API。接下来以阿里云为例,介绍如何实现短信发送功能,其他短信服务商也是类似的操作。

2、短信发送逻辑

阿里云短信发送逻辑大致总结为:提供登录阿里云的账号(AccessKey ID)和密码(AccessKey Secret)登录后,选择对应的短信签名模版,填充对应的短信内容(模版参数),然后将短信发送到指定的手机号

签名:短信开头时【】内的公司信息

模板:短信内容的骨架,可填充对应参数

注意:阿里云短信服务申请签名主要针对企业开发,个人申请时有一定难度,在审核时会审核资质,需要上传营业执。但阿里云提供了测试签名和测试模板,开发测试时只需要获取对应的测试签名和测试模板。

  • 获取AccessKeyId和AccessKeySecret,点击头像右上角的AccessKey管理按钮后获取。

  • 获取测试签名和模板

3、代码实现

目前阿里云短信服务的SDK分为1.0版本和2.0版本,1.0已经不再维护,推荐使用2.0版本,下面列举了两种方式的实现代码。

  • 2.0版本

(1) Maven方式引入pom依赖

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

(2) 代码编写

代码逻辑:创建发送短信的客户端,提供参数调用对应方法即可。 需要提供下面几个参数:

  • AccessKey ID:类似登录阿里云时的账号
  • AccessKey Secret:类似登录阿里云的密码
  • phone:接收短信的号码
  • signName:短信签名,即短信开头时【】内的公司信息
  • templateCode:模版编码,即短信内容的骨架
  • templateParam:模版参数,即要往短信模版骨架中填充的内容
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.models.RuntimeOptions;

public class SMSUtils {
    /**
     * 阿里云登录id
     */
    private final static String ACCESS_KEY_ID = "your access key id";

    /**
     * 阿里云登录密码
     */
    private final static String ACCESS_KEY_SECRET = "your access key secret";

    /**
     * 初始化登录阿里云的Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
        .setAccessKeyId(accessKeyId)
        .setAccessKeySecret(accessKeySecret);
        // 可指定登录的服务器地址,可参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    /**
     * 发送短信方法
     * @param phoneNumbers 手机号
     * @param signName 签名
     * @param templateCode  模板编号
     * @param param 模板参数
     * @throws Exception
     */
    public static void sendMessage(String phoneNumbers, String signName, String templateCode, String param) throws Exception {
        com.aliyun.dysmsapi20170525.Client client = SMSUtils.createClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
        .setPhoneNumbers(phoneNumbers)
        .setSignName(signName)
        .setTemplateCode(templateCode)
        .setTemplateParam(param);
        SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());
        System.out.println("短信发送成功,返回结果是:"+sendSmsResponse);
    }

    public static void main(String[] args) {
        try {
            SMSUtils.sendMessage("15179068888", "阿里云短信测试", "SMS_154958888", "{\"code\":\"7777\"}");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

  • 1.0版本

(1) Maven方式引入pom依赖

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.5.16</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
    <version>2.1.0</version>
</dependency>

(2) 代码编写

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;

/**
 * 短信发送工具类
 */
public class SMSUtils {
   /**
    * 发送短信
    * @param signName 签名
    * @param templateCode 模板
    * @param phoneNumbers 手机号
    * @param param 模板参数
    */
   public static void sendMessage(String signName, String templateCode,String phoneNumbers,String param){
      // client的参数,服务器ip, accessKeyId, accessKeySecret 
      DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "xxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxx");
      // 登录client
      IAcsClient client = new DefaultAcsClient(profile);

      SendSmsRequest request = new SendSmsRequest();
      request.setSysRegionId("cn-hangzhou");
      request.setPhoneNumbers(phoneNumbers);
      request.setSignName(signName);
      request.setTemplateCode(templateCode);
      request.setTemplateParam("{\"code\":\""+param+"\"}");
      try {
         SendSmsResponse response = client.getAcsResponse(request);
         System.out.println("短信发送成功");
      }catch (ClientException e) {
         e.printStackTrace();
      }
   }
}
Java发送短信到手机通常涉及到第三方短信服务提供商的API,因为标准的Java库并不直接支持这个功能。这里是一个基本的步骤概述: 1. 注册并获取短信服务API密钥:首先,你需要选择一个提供短信API的服务,如Twilio、 Nexmo 或者阿里云等。注册并获取相应的API账号。 2. 添加依赖:如果服务商提供了SDK,你可能需要将它们添加到你的项目中。例如,对于Twilio,你可以通过Maven或Gradle添加`twilio-java-sdk`库。 ```xml <!-- Maven --> <dependency> <groupId>com.twilio.sdk</groupId> <artifactId>twilio-java-sdk</artifactId> <version>7.59.0</version> </dependency> // Gradle implementation 'com.twilio.sdk:twilio-java-sdk:7.59.0' ``` 3. 初始化客户端:设置API密钥来初始化短信客户端。 ```java import com.twilio.rest.api.v2010.account.Message; // Twilio示例 String accountSid = "your_account_sid"; String authToken = "your_auth_token"; MessageServiceClient client = MessageServiceClient.create(accountSid, authToken); ``` 4. 发送短信:创建一个新的消息实例,指定接收者的电话号码和短信内容,然后调用`create()`方法发送。 ```java try { String toNumber = "+1234567890"; // 替换为实际手机号码 Map<String, Object> params = new HashMap<>(); params.put("body", "Hello from Java! This is a test message."); Message message = client.messages.create(toNumber, params); System.out.println("SMS sent with SID: " + message.getSid()); } catch (Exception e) { e.printStackTrace(); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值