阿里云短信服务不对个人开放?如何在阿里云市场免费购买短信服务?云市场购买到的短信服务如何使用?(以谷粒学院项目为例)
Posted 是奶盖的妈咪呀
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了阿里云短信服务不对个人开放?如何在阿里云市场免费购买短信服务?云市场购买到的短信服务如何使用?(以谷粒学院项目为例)相关的知识,希望对你有一定的参考价值。
问题描述:
在做谷粒学院项目时,需要使用阿里云的短信服务用于注册验证,但是阿里云的短信服务目前不对个人开放了,看到弹幕说可以在云市场购买,于是果断尝试了一把,这过程中又遇到头疼的依赖版本兼容问题,好在最终解决并测试成功了。在此把详细的操作流程分享给大家。(如果是谷粒学院项目,代码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>();
// 生成随机数字并存入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;
第四步:编写service层和controller层
service接口:
service层实现类:(注意:appcode写自己的)
@Service
public class MsmServiceImpl implements MsmService
@Override
public void send(String phone)
//调用地址:http(s)://jumsendsms.market.alicloudapi.com/sms/send-upgrade
String host = "https://jumsendsms.market.alicloudapi.com";
String path = "/sms/send-upgrade";
String method = "POST";
//自己的appcode
String appcode = "自己的appcode";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);
String random = RandomUtil.getFourBitRandom();
Map<String, String> querys = new HashMap<String, String>();
querys.put("mobile", phone);
//使用服务商提供的测试模板id
querys.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的body
System.out.println(EntityUtils.toString(response.getEntity()));
catch (Exception e)
e.printStackTrace();
controller层调用:
@RestController
@RequestMapping("/edumsm")
@CrossOrigin(allowCredentials = "true")
public class MsmController
@Autowired
private MsmService msmService;
@GetMapping("/send/phone")
public R send(@PathVariable("phone")String phone)
msmService.send(phone);
return R.ok();
第五步:启动项目测试。
如有问题,欢迎留言。
以上是关于阿里云短信服务不对个人开放?如何在阿里云市场免费购买短信服务?云市场购买到的短信服务如何使用?(以谷粒学院项目为例)的主要内容,如果未能解决你的问题,请参考以下文章