阿里云_山东鼎信短信的使用(云市场)

news2024/9/28 7:26:38

目录

  • 山东鼎信API工具类
  • 随机验证码工具类
  • 进行测试
    • Pom依赖(可以先导入依赖)
    • 创建controller
    • SmsService
    • SmsServiceImpl
    • swagger测试(也可以使用postman)

山东鼎信API工具类

山东鼎信短信官网
找到java的Api,复制下来
在这里插入图片描述
适当改了一下,为了调用(类名SmsUtils)

public static void sendShortMessage(String phoneNumbers,String param){
        String host = "http://dingxin.market.alicloudapi.com";
        String path = "/dx/sendSms";
        String method = "POST";
        String appcode = "你的 appcode";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phoneNumbers);
        querys.put("param", "code:"+param);
        querys.put("tpl_id", "TP1711063");
        Map<String, String> bodys = new HashMap<String, String>();


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

代码中的appcode在控制台的云市场
在这里插入图片描述
然后会发现HttpUtils爆红,然后也给了我们提示
然后进入网址,把代码拷贝下来就行了
在这里插入图片描述

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpUtils {
	
	/**
	 * get
	 * 
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doGet(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }
        
        return httpClient.execute(request);
    }
	
	/**
	 * post form
	 * 
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param bodys
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doPost(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys, 
			Map<String, String> bodys)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }

        return httpClient.execute(request);
    }	
	
	/**
	 * Post String
	 * 
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param body
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doPost(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys, 
			String body)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
        	request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }
	
	/**
	 * Post stream
	 * 
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param body
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doPost(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys, 
			byte[] body)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
        	request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }
	
	/**
	 * Put String
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param body
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doPut(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys, 
			String body)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
        	request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }
	
	/**
	 * Put stream
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param body
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doPut(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys, 
			byte[] body)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
        	request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }
	
	/**
	 * Delete
	 *  
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @return
	 * @throws Exception
	 */
	public static HttpResponse doDelete(String host, String path, String method, 
			Map<String, String> headers, 
			Map<String, String> querys)
            throws Exception {    	
    	HttpClient httpClient = wrapClient(host);

    	HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
        	request.addHeader(e.getKey(), e.getValue());
        }
        
        return httpClient.execute(request);
    }
	
	private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
    	StringBuilder sbUrl = new StringBuilder();
    	sbUrl.append(host);
    	if (!StringUtils.isBlank(path)) {
    		sbUrl.append(path);
        }
    	if (null != querys) {
    		StringBuilder sbQuery = new StringBuilder();
        	for (Map.Entry<String, String> query : querys.entrySet()) {
        		if (0 < sbQuery.length()) {
        			sbQuery.append("&");
        		}
        		if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
        			sbQuery.append(query.getValue());
                }
        		if (!StringUtils.isBlank(query.getKey())) {
        			sbQuery.append(query.getKey());
        			if (!StringUtils.isBlank(query.getValue())) {
        				sbQuery.append("=");
        				sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
        			}        			
                }
        	}
        	if (0 < sbQuery.length()) {
        		sbUrl.append("?").append(sbQuery);
        	}
        }
    	
    	return sbUrl.toString();
    }
	
	private static HttpClient wrapClient(String host) {
		HttpClient httpClient = new DefaultHttpClient();
		if (host.startsWith("https://")) {
			sslClient(httpClient);
		}
		
		return httpClient;
	}
	
	private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(X509Certificate[] xcs, String str) {
                	
                }
                public void checkServerTrusted(X509Certificate[] xcs, String str) {
                	
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
        	throw new RuntimeException(ex);
        }
    }
}

随机验证码工具类

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * 获取随机数
 * 
 * @author qianyi
 *
 */
public class RandomUtil {

	private static final Random random = new Random();

	private static final DecimalFormat fourdf = new DecimalFormat("0000");

	private static final DecimalFormat sixdf = new DecimalFormat("000000");

	public static String getFourBitRandom() {
		return fourdf.format(random.nextInt(10000));
	}

	public static String getSixBitRandom() {
		return sixdf.format(random.nextInt(1000000));
	}

	/**
	 * 给定数组,抽取n个数据
	 * @param list
	 * @param n
	 * @return
	 */
	public static ArrayList getRandom(List list, int n) {

		Random random = new Random();

		HashMap<Object, Object> hashMap = new HashMap<Object, Object>();

		// 生成随机数字并存入HashMap
		for (int i = 0; i < list.size(); i++) {

			int number = random.nextInt(100) + 1;

			hashMap.put(number, i);
		}

		// 从HashMap导入数组
		Object[] robjs = hashMap.values().toArray();

		ArrayList r = new ArrayList();

		// 遍历数组并打印数据
		for (int i = 0; i < n; i++) {
			r.add(list.get((int) robjs[i]));
			System.out.print(list.get((int) robjs[i]) + "\t");
		}
		System.out.print("\n");
		return r;
	}
}

进行测试

Pom依赖(可以先导入依赖)

    <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>

创建controller

import com.donglin.commonutils.R;
import com.donglin.smsservice.service.SmsService;
import com.donglin.smsservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.TimeUnit;

@Api(description = "短息发送")
@RestController
@RequestMapping("/edusms/sms")
@CrossOrigin //跨域
public class SmsApiController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @ApiOperation(value = "短信发送")
    @GetMapping("send/{phone}")
    public R sendSmsPhone(@PathVariable String phone){
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code))
            return R.ok();

        code = RandomUtil.getFourBitRandom();
        boolean isSend = smsService.send(phone, code);
        if(isSend) {
            redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("发送短信失败");
        }

    }
}

SmsService

public interface SmsService {

    boolean send(String phone, String code);
}

SmsServiceImpl

import com.donglin.smsservice.service.SmsService;
import com.donglin.smsservice.utils.SmsUtils;
import org.springframework.stereotype.Service;

import java.rmi.ServerException;

@Service
public class SmsServiceImpl implements SmsService {

    @Override
    public boolean send(String phone, String code) {
        try {
            SmsUtils.sendShortMessage(phone,code);
            System.out.println("phone = " + phone);
            System.out.println("code = " + code);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

swagger测试(也可以使用postman)

在这里插入图片描述

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

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

相关文章

GEE学习笔记 七十二:【GEE之Python版教程六】命令行简介

这篇开始就要讲解GEE相关的内容&#xff0c;首先聊一下命令行的内容&#xff0c;这个在官方文档中有详细的介绍&#xff0c;这里我简单说一下常用的几个命令&#xff0c;剩余的大家在使用过程中如果又需要可以随时查看相关官方文档的介绍。官方文档地址&#xff1a;https://dev…

pcie link training

有机会用瑞芯微做EP&#xff0c;X86做RC &#xff0c;调试两者建立连接。环境配置如图所示&#xff0c;两块单板&#xff0c;期望瑞芯微做EP&#xff0c;X86做RC&#xff0c;两者能够互联。LINK 配置过程主要配置瑞芯微瑞芯微的芯片配置&#xff0c;在配置EP模式时&#xff0c;…

5.2 BGP水平分割

5.2.2实验2&#xff1a;BGP水平分割 1. 实验目的 熟悉BGP水平分割的应用场景掌握BGP水平分割的配置方法 2. 实验拓扑 实验拓扑如图5-2所示&#xff1a; 图5-2&#xff1a;BGP水平分割 3. 实验步骤 &#xff08;1&#xff09;配置IP地址 R1的配置 <Huawei>…

GEE学习笔记 七十五:【GEE之Python版教程九】数值

这章介绍一下数值类型&#xff0c;数值在python中可以分为&#xff1a;整型、浮点型、复数等&#xff0c;在GEE中我们常用的就是整形和浮点型数据。 这段代码是在程序之前必须执行的&#xff0c;用来注册GEE。 import ee ee.Initialize() 1、数值的API 首先看一下GEE的pytho…

一文读懂select、poll、epoll的用法

select&#xff0c;poll&#xff0c;epoll都是IO多路复用的机制。I/O多路复用就通过一种机制&#xff0c;可以监视多个描述符&#xff0c;一旦某个描述符就绪&#xff08;一般是读就绪或者写就绪&#xff09;&#xff0c;能够通知程序进行相应的读写操作。但select&#xff0c;…

一些有用的shell命令盘点

1、ssh 说明&#xff1a; ssh命令是经常用来连接服务器的&#xff0c;如何使用ssh命令连接服务器是一个后端开发必备的技能&#xff0c;当你需要查看服务器上日志等信息时&#xff0c;就需要使用该命令来登录到服务器进行查看。 使用&#xff1a; ssh $USERNAME$IP例如&#…

Python程序打包exe可执行软件教程

1、前言Python虽好&#xff0c;但是平时我们写的代码都是.py脚本文件&#xff0c;必须要在Python环境下 才可以运行。如果一台电脑没有安装Python是无法运行我们的程序的。当然你也可以选择随身携带安装包。 不过终究是有些麻烦。那么有没有什么办法&#xff0c;能把我们编写的…

【扬尘监测系统】让扬尘管理迈向“智慧化”

扬尘是指道路与管线施工、物料运输、物料堆放、植物栽种和养护等活动产生的粉尘颗粒物对大气造成的污染。 治理扬尘污染&#xff0c;我们应该从源头出发&#xff0c;进行“防治”。扬尘监测系统是利用现代科学技术对扬尘的排放程度进行客观、科学、准确的量化和评价的设备&…

零信任-易安联零信任介绍(11)

​目录 ​易安联零信任公司介绍 易安联零信任发展路线 易安联零信任产品介绍 易安联零信任架构 易安联零信任解决方案 易安联零信任发展展望 易安联零信任公司介绍 易安联是一家专业从事网络信息安全产品研发与销售&#xff0c;是行业内领先的“零信任”解决方案提供商&…

ChatGPT或将引发新一轮失业潮?是真的吗?

最近&#xff0c;要说有什么热度不减的话题&#xff0c;那ChatGPT必然榜上有名。据悉是这是由美国人工智能研究实验室OpenAI开发的一种全新聊天机器人模型&#xff0c;它能够通过学习和理解人类的语言来进行对话&#xff0c;还能根据聊天的上下文进行互动&#xff0c;并协助人类…

6.2 构建 RESTful 应用接口

第6章 构建 RESTful 服务 6.1 RESTful 简介 6.2 构建 RESTful 应用接口 6.3 使用 Swagger 生成 Web API 文档 6.4 实战&#xff1a;实现 Web API 版本控制 6.2 构建 RESTful 应用接口 6.2.1 Spring Boot 对 RESTful 的支持 Spring Boot 提供的spring-boot-starter-web组件完全…

Pygame中画圆

在Pygame中&#xff0c;可以通过draw模块下的circle()函数来进行画圆。1 准备工作的完成在画圆之前需要导入Pygame模块、初始化Pygame模块以及创建Surface对象。import pygame from pygame.locals import * pygame.init() screen pygame.display.set_mode((600,500))其中&…

SpringBoot实现 内置 定时 发送邮件功能

前段时间因为公司用了定时任务&#xff0c;所以写了2篇定时任务的文章&#xff0c;一篇是正常如何在Springboot 编程中如何去使用quartz &#xff0c;第二篇就是 正常业务性的增删改查&#xff0c;今天我们来看下如何使用 quartz 去定时给女朋友发邮件 &#xff0c;结尾会放上完…

智能电子办公标牌解决方案

一、WiFi智能电子标牌 智能电子办公标牌将它放在任何地方&#xff0c;以可视化会议日程、约会信息、行动计划和协作任务&#xff0c;使团队能够更有效地工作并更好地利用空间。 优势&#xff1a; ● 超低功耗&#xff0c;充一次电管用一年&#xff0c;支持Type-C接口充电 ●…

Linux之进程

一.冯诺依曼体系 在计算机中&#xff0c;CPU&#xff08;中央处理器&#xff09;是不直接跟外部设备直接进行通信的&#xff0c;因为CPU处理速度太快了&#xff0c;而设备的数据读取和输入有太慢&#xff0c;而是CPU以及外设直接跟存储器&#xff08;内存&#xff09;打交道&am…

Python 之 Matplotlib 柱状图(竖直柱状图和水平柱状图)、直方图和饼状图

文章目录一、柱状图二、竖直柱状图1. 基本的柱状图2. 同位置多柱状图3. 堆叠柱状图三、水平柱状图1. 基本的柱状图2. 同位置多柱状图3. 堆叠柱状图四、直方图 plt.hist()1. 返回值2. 添加折线直方图3. 不等距分组4. 多类型直方图5. 堆叠直方图五、饼状图 pie()1. 百分比显示 pe…

初步使用MSYS2

在此镜像站点下载&#xff0c; https://mirror.tuna.tsinghua.edu.cn/help/msys2/ 根据资料&#xff0c; MSYS2 &#xff08;Minimal SYStem 2&#xff09; 是一个MSYS的独立改写版本&#xff0c;主要用于 shell 命令行开发环境。同时它也是一个在Cygwin &#xff08;POSIX …

FPGA 10M50DCF672C7G/10M50DCF672C8G/10M50DCF672I7G工业、汽车和消费应用

FPGA现场可编程门阵列 10M50DCF672C7G/10M50DCF672C8G/10M50DCF672I7G 封装FBGA672FBGA672封装图&#xff08;明佳达电子&#xff09;描述MAX 10器件是单芯片、非易失性低成本可编程逻辑器件(pld)&#xff0c;用于集成最优的系统组件集。MAX 10设备的亮点包括:内部存储双配置闪…

Spring Data JPA 中 CrudRepository 和 JpaRepository 的区别

1 问题描述Spring Data JPA 中&#xff0c;CrudRepository 和 JpaRepository 有何区别&#xff1f;当我在网上找例子的时候&#xff0c;发现它们可以互相替换使用。它们有什么不同呢&#xff1f;为什么你习惯用其中的一个而不是另一个呢&#xff1f;2 CrudRepository 和 JpaRep…

ArcGIS网络分析之发布网络分析服务(二)

在上一篇中讲述了如何构建网络分析数据集,本篇将讲解如何发布网络分析服务。本文将使用上一篇中建立的网络数据集,下载地址在上一篇博文的最后已给出。 之前我们已经实现了基于ArcMap中的网络分析,但是仅仅支持本地是万万不够的,这里我们的目的就是将我们建好的网络分析图…