问题描述

在做谷粒学院项目时,需要使用阿里云的短信服务用于注册验证,但是阿里云的短信服务目前不对个人开放了,看到弹幕说可以在云市场购买,于是果断尝试了一把,这过程中又遇到头疼的依赖版本兼容问题,好在最终解决并测试成功了。在此把详细的操作流程分享给大家。(如果是谷粒学院项目,代码c-v即可)

具体操作步骤:

第一步:进入阿里云官网的云市场,搜索短信,我选的是下面的短信服务。(5条短信以内不要钱!不要钱!不要钱!)

第二步:添加相关依赖,直接复制以下依赖即可,亲测好使。(供应商提供的依赖版本过低)

    <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.5.10</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.12</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><dependency><groupId>org.eclipse.jetty</groupId><artifactId>jetty-util</artifactId><version>9.3.7.v20160115</version></dependency></dependencies>

 第三步:添加以下两个工具类HttpUtils(用于发送验证码的servlet工具类)和RandomUtil(生成随机的验证码)。

提示:短信服务只是帮我们发送短信的,而验证码是程序生成的。

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);}}
}
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>();// 生成随机数字并存入HashMapfor (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;}
}

第四步:编写service层和controller层

service接口:

service层实现类:(注意:appcode写自己的

@Service
public class MsmServiceImpl implements MsmService {@Overridepublic void send(String phone) {//调用地址:http(s)://jumsendsms.market.alicloudapi.com/sms/send-upgradeString host = "https://jumsendsms.market.alicloudapi.com";String path = "/sms/send-upgrade";String method = "POST";//自己的appcodeString appcode = "自己的appcode";Map<String, String> headers = new HashMap<String, String>();//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105headers.put("Authorization", "APPCODE " + appcode);String random = RandomUtil.getFourBitRandom();Map<String, String> querys = new HashMap<String, String>();querys.put("mobile", phone);//使用服务商提供的测试模板idquerys.put("templateId", "M105EABDEC");querys.put("value", random);Map<String, String> bodys = new HashMap<String, String>();try {HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);System.out.println(response.toString());//获取response的bodySystem.out.println(EntityUtils.toString(response.getEntity()));} catch (Exception e) {e.printStackTrace();}}
}

controller层调用:

@RestController
@RequestMapping("/edumsm")
@CrossOrigin(allowCredentials = "true")
public class MsmController {@Autowiredprivate MsmService msmService;@GetMapping("/send/{phone}")public R send(@PathVariable("phone")String phone){msmService.send(phone);return R.ok();}
}

第五步:启动项目测试。

如有问题,欢迎留言。

阿里云短信服务不对个人开放?如何在阿里云市场免费购买短信服务?云市场购买到的短信服务如何使用?(以谷粒学院项目为例)相关推荐

  1. EMW3080 STC15轻松实现设备上云3(阿里云物联网平台、智能生活开放平台)

    警告:本系列教程针对ILOP.A221固件开发,如使用其他ILOP固件,请自行修改配网部分.数据上报部分及解析服务器下发信息部分! 从本节开始我们就开始写程序用STC15单片机了实现设备上云啦!在此之 ...

  2. Day210.服务端渲染技术NUXT、整合前台主页面、名师、课程静态页面、首页整合banner数据后端部分【创建banner微服务、接口、banner后台前端实现】 -谷粒学院

    谷粒学院 服务端渲染技术NUXT 一.服务端渲染技术NUXT 1.什么是服务端渲染 服务端渲染又称SSR (Server Side Render)是在服务端完成页面的内容,而不是在客户端通过AJAX获 ...

  3. 谷粒学院(十五)JWT | 阿里云短信服务 | 登录与注册前后端实现

    文章目录 一.使用JWT进行跨域身份验证 1.传统用户身份验证 2.解决方案 二.JWT令牌 1.访问令牌的类型 2.JWT的组成 3.JWT的原则 4.JWT的用法 三.整合JWT令牌 1.在com ...

  4. 阿里云与WPS深度合作,开放数据处理生态

    摘要: 在3月28日举行的2018云栖大会-深圳峰会上,阿里云与金山办公达成深度合作,WPS在线预览与格式转换能力落地阿里云.标志着阿里云存储开放的数据湖体系不但面向计算引擎,还面向应用开放. 在3月 ...

  5. 阿里云飞天洛神2.0:开放弹性的云网络NFV平台

    云网络架构 阿里云操作系统叫飞天,云网络平台称为洛神.作为飞天系统的核心组件,洛神平台支撑了超大规模租户.超大规模虚拟机的高性能云网络. 洛神平台由很多网络设备组成,在架构上主要可以分为两类:虚拟交换 ...

  6. 【云服务架构】什么是云原生应用?有哪些特点?来看看阿里云大学公开课给你答案

    云原生技术发展简史 首先从第一个问题进行分享,那就是"为什么要开设云原生技术公开课?"云原生.CNCF 都是目前非常热门的关键词,但是这些技术并不是非常新鲜的内容. 2004 年- ...

  7. 三大巨头遥遥领先!亚马逊云服务领跑亚太第一,阿里微软紧随其后,腾讯谷歌百度进入前六 | 美通社头条...

    要闻摘要:亚马逊云服务领跑亚太第一,阿里微软紧随其后.IBM任命陈旭东担任大中华区总经理.前霍尼韦尔全球高增长区总裁兼CEO创建国际投资集团睿桥.霍尼韦尔推出氢燃烧解决方案服务组合.国际权威机构碳信托 ...

  8. 新一代微服务全家桶AlibabaCloud+Docker+JDK11阿里云容器部署零基础到项目实战

    新一代微服务全家桶AlibabaCloud+Docker+JDK11阿里云容器部署零基础到项目实战 近年来,微服务架构已经成为企业标配,它以更加灵活的部署方式和高度解耦的架构设计,为企业带来了极大的业 ...

  9. 阿里云服务器ECS windows server已开放端口但连不上的问题

    阿里云服务器ECS上已经开放了相应端口的安全组,云服务器的防火墙也已经关闭了. 阿里云服务器自带的安全组3389端口能脸上,但自定义开的端口22和8080连不上: 阿里云服务器的防火墙通过远程桌面连接 ...

最新文章

  1. DataGrid的使用
  2. matlab在绘图区加格栅,实验二(2) MATLAB绘图
  3. ubuntu 进入 recovery mode
  4. TCP如何能正常关闭连接?
  5. vb.net datagridview数据批量导入sql_导入:Java实现大批量数据导入导出(100W以上)
  6. a标签传参接收_[pyecharts1.8] 系列配置之标签设置
  7. tankwar的java坦克子弹撞墙_tankwar
  8. Django——序列化与反序列化
  9. 多目标跟踪——MOT算法的学习笔记
  10. [情感]富裕的女人守不住爱情
  11. 03-树2. List Leaves (25) 二叉树的层序遍历
  12. 【目标检测】SSD中的hard negative mining
  13. Android应用程序消息处理机制(Looper、Handler)分析(3)
  14. 计算机软件行业职业病,IT行业的六大职业病,看看你有没有中
  15. mongodb:修改oplog.rs 的大小size
  16. Qlocker勒索病毒 7Z勒索病毒 7Z压缩包密码破解
  17. 刺激战场测试fps软件,绝地求生刺激战场通过GLTools实时显示游戏帧数方法
  18. 烽火计划项目成果-目录索引
  19. 如何提高自身跟团队的领导力?
  20. 网络规划设计师复习笔记--网络需求分析

热门文章

  1. vue element上传额外参数
  2. 电商系统购物车设计思路
  3. 什么是ISO?ISO增值的作用
  4. Android中点击链接调起App
  5. 日常猜幸运数字小游戏
  6. 我的优点是会使用计算机用英语怎,优点用英语,我的50个优点。
  7. 51单片机的键盘检测原理
  8. WPF中的MVVM模式
  9. java暗装没有快捷键_全网最全最硬最实用的idea 使用技巧与快捷键,开发必备的百分百快捷键...
  10. 成都榆熙:拼多多商家都想要提高客单价,但是怎么去提高呢?