阿里云短信服务Java版

短信服务管理平台 https://dysms.console.aliyun.com/dysms.htm

java短信发送API    https://help.aliyun.com/document_detail/55284.html?spm=5176.10629532.106.1.614b1cbe9VbjhP

过程注册信息API都有

1.发送短信实现类

package com.xmg.p2p.base.service.impl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.xmg.p2p.base.service.IPhoneService;

@Service
public class PhoneServiceImpl implements IPhoneService {

    @Value("${AccessKeyId}")
    private String mYAccessKeyId;
    @Value("${AccessKeySecret}")
    private String mYAccessKeySecret;
    @Value("${SignName}")
    private String SignName;
    @Value("${TemplateCode}")
    private String TemplateCode;

    @Override
    public void sendPhone(String username,String PhoneNumbers,String code) {
        try {
            //2: 编写样例程序
            //注:有备注无需修改的位置请勿改动。
            //设置超时时间-可自行调整
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            //初始化ascClient需要的几个参数
            final String product = "Dysmsapi";//短信API产品名称(短信产品名固定,无需修改)
            final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名(接口地址固定,无需修改)
            //替换成你的AK
            final String accessKeyId = mYAccessKeyId;//你的accessKeyId,参考本文档步骤2
            final String accessKeySecret = mYAccessKeySecret;//你的accessKeySecret,参考本文档步骤2
            //初始化ascClient,暂时不支持多region(请勿修改)
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
            accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
             //组装请求对象
             SendSmsRequest request = new SendSmsRequest();
             //使用post提交
             request.setMethod(MethodType.POST);
             request.setEncoding("UTF-8");
             //必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
             request.setPhoneNumbers(PhoneNumbers);
             //必填:短信签名-可在短信控制台中找到
             request.setSignName(SignName);
             //必填:短信模板-可在短信控制台中找到
             request.setTemplateCode(TemplateCode);

             //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
             //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
             request.setTemplateParam("{\"name\":\"111\", \"code\":\""+code+"\"}");
             //可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
             //request.setSmsUpExtendCode("90997");
             //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
          //     request.setOutId("yourOutId");
            //请求失败这里会抛ClientException异常
            System.out.println("============");
            try {
                SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

                System.out.println("Code:"+sendSmsResponse.getCode());
                if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {

                    //请求成功
                    System.out.println("请求成功");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {

        }

    }

}

2.配置文件

#均为阿里云API注册信息
AccessKeyId=***
AccessKeySecret=***
SignName=***
TemplateCode=SMS_***

3.测试类

package com.xmg.test;

import java.util.UUID;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.xmg.p2p.base.service.IMailService;
import com.xmg.p2p.base.service.IPhoneService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SendMailTest {

    @Autowired
    private IPhoneService phoneService;

    @Test
    public void testSendPhone(){
        //生成一个验证码
        String verifyCode = UUID.randomUUID().toString().substring(0,4);
        phoneService.sendPhone("zzz","130****6583",  verifyCode);
    }
}

但是采用测试类直接运行会报错

java.lang.RuntimeException: HMAC-SHA1 not supported.
    at com.aliyuncs.auth.ShaHmac1.signString(ShaHmac1.java:44)
    at com.aliyuncs.RpcAcsRequest.signRequest(RpcAcsRequest.java:138)
    at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:232)
    at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:175)
    at com.aliyuncs.DefaultAcsClient.doAction(DefaultAcsClient.java:79)
    at com.aliyuncs.DefaultAcsClient.getAcsResponse(DefaultAcsClient.java:124)
    at com.xmg.p2p.base.service.impl.PhoneServiceImpl.sendPhone(PhoneServiceImpl.java:69)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy30.sendPhone(Unknown Source)
    at com.xmg.test.SendMailTest.testSendPhone(SendMailTest.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

百度查找原因也说找不到jar包 不过工程jar包都在(不知道测试类直接运行为什么报错   望大神解释下)

然而 我在maven install把工程打成jar包时却能正常运行  并且能正常返回结果码并且正常发送短信

原文地址:https://www.cnblogs.com/jokerq/p/8601646.html

时间: 2024-08-29 06:34:52

阿里云短信服务Java版的相关文章

调用阿里云短信服务

package com.example.demo.untils; /** * Created by JQY on 2019/5/15 */ import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; import com.aliyuncs.dysmsapi.model.v20170525.Send

Zabbix 3.4.3 使用阿里云短信服务进行报警

一.阿里云短信服务 有时候微信报警或者邮寄报警我们可能会有遗忘,今天我主要介绍使用阿里云的短信服务进行短信报警. 1.1.首先开通阿里云短信服务 1.2 创建签名 签名用途选择:公众号或小程序的全称或简称 就可以了. 1.3 创建短信模板 1.4 创建发送脚本 创建脚本sendsms.py,放到 zabbix 脚本路径,记得在配置文件开启AlertScriptsPath=路径,我们向脚本传递两个参数,一个是手机号,一个是信息,信息里面包含三个字段(主机IP,时间,内容),由我们下面的 Media

阿里云短信服务调用例子-Python

阿里云短信服务调用例子 阿里云官方文档https://helpcdn.aliyun.com/document_detail/101893.html 首先需要安装阿里云PythonSDK(下面是python3版本的安装方式) pip install aliyun-python-sdk-core-v3 阿里云官方调用例子 #!/usr/bin/env python #coding=utf-8 from aliyunsdkcore.client import AcsClient from aliyun

yii2 阿里云 短信服务 aliyun_dysms [ 2.0 版本 ]

安装 1 composer require "saviorlv/yii2-dysms:dev-master" or添加下列代码在composer.json文件中并执行composer update 操作 1 2 3 4 5 { "require": { "saviorlv/yii2-dysms":"dev-master" } } 设置方法 全局使用 在config/main.php配置文件中定义component配置信息 1

使用阿里云短信服务发送短信验证码

阿里云短发服务使用流程: 1.在阿里云上完成短信服务的购买. 2.导入相关的jar包. <!-- 阿里云短信服务 --> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.1.0</version> </dependency> <!-- 阿里云短

阿里云短信服务(JAVA)

一,前言 ? 短信验证码想必大家都不陌生,在很多网站,APP中都有使用到.比如登录,注册,身份校验等场景.不过通常情况下,短信服务都是外包给第三方公司的,接下来向大家分享如何使用阿里的短信服务. 二,云通信 ? 阿里云官网:https://www.aliyun.com/ ? 忘记说了,没有账号的可以直接使用阿里旗下的任何一款账号进行登录,支付宝,淘宝,钉钉等都可以,或者也可以单独进行注册,这里就不再讲述如何注册了. ? 登录成功以后,首页如下,在上方搜索框中搜索短信服务: ? ? 1,点击短信服

阿里云短信服务报错org.json.JSONArray.iterator()Ljava/util/Iterator

maven依赖如下: <!-- 阿里云短信sdk --> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>3.7.1</version> </dependency> <dependency> <groupId>com.aliyun

阿里云短信服务验证码模板

<?php namespace app\api\controller; use think\Db; use think\Request; use think\Controller; /** * 阿里云短信验证码发送类 * @author Administrator * */ class Smscode { // 保存错误信息 public $error; // Access Key ID private $accessKeyId = ''; // Access Access Key Secret

阿里云短信服务发送短信验证码(JAVA开发此功能)

开发此功能需注册阿里云账号,并开通短信服务(免费开通) 充值后,不会影响业务的正常使用!(因为发送验证类短信:1-10万范围的短信是0.045元/条).开发测试使用,充2块钱测试足够了 可参考阿里云官方开发文档了解详情,文档中写的也是很详细了... https://help.aliyun.com/product/44282.html 代码编写之前需要准备几个东西 1,aliyun-java-sdk-core.jar ,  aliyun-java-sdk-dysmsapi.jar  这2个jar包