当前位置:   article > 正文

阿里云发送短信配置

阿里云发送短信配置

依赖

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.2.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.httpcomponents</groupId>
  8. <artifactId>httpcore</artifactId>
  9. <version>4.2.1</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>commons-lang</groupId>
  13. <artifactId>commons-lang</artifactId>
  14. <version>2.6</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.eclipse.jetty</groupId>
  18. <artifactId>jetty-util</artifactId>
  19. <version>9.3.7.v20160115</version>
  20. </dependency>
  21. <!-- redis的起步依赖 -->
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-data-redis</artifactId>
  25. </dependency>

配置类

  1. import org.apache.commons.lang.StringUtils;
  2. import org.apache.http.HttpResponse;
  3. import org.apache.http.NameValuePair;
  4. import org.apache.http.client.HttpClient;
  5. import org.apache.http.client.entity.UrlEncodedFormEntity;
  6. import org.apache.http.client.methods.HttpDelete;
  7. import org.apache.http.client.methods.HttpGet;
  8. import org.apache.http.client.methods.HttpPost;
  9. import org.apache.http.client.methods.HttpPut;
  10. import org.apache.http.conn.ClientConnectionManager;
  11. import org.apache.http.conn.scheme.Scheme;
  12. import org.apache.http.conn.scheme.SchemeRegistry;
  13. import org.apache.http.conn.scheme.SchemeSocketFactory;
  14. import org.apache.http.conn.ssl.SSLSocketFactory;
  15. import org.apache.http.entity.ByteArrayEntity;
  16. import org.apache.http.entity.StringEntity;
  17. import org.apache.http.impl.client.DefaultHttpClient;
  18. import org.apache.http.message.BasicNameValuePair;
  19. import javax.net.ssl.SSLContext;
  20. import javax.net.ssl.TrustManager;
  21. import javax.net.ssl.X509TrustManager;
  22. import java.io.UnsupportedEncodingException;
  23. import java.net.URLEncoder;
  24. import java.security.KeyManagementException;
  25. import java.security.NoSuchAlgorithmException;
  26. import java.security.cert.X509Certificate;
  27. import java.util.ArrayList;
  28. import java.util.List;
  29. import java.util.Map;
  30. public class HttpUtils {
  31. /**
  32. * get
  33. *
  34. * @param host
  35. * @param path
  36. * @param method
  37. * @param headers
  38. * @param querys
  39. * @return
  40. * @throws Exception
  41. */
  42. public static HttpResponse doGet(String host, String path, String method,
  43. Map<String, String> headers,
  44. Map<String, String> querys)
  45. throws Exception {
  46. HttpClient httpClient = wrapClient(host);
  47. HttpGet request = new HttpGet(buildUrl(host, path, querys));
  48. for (Map.Entry<String, String> e : headers.entrySet()) {
  49. request.addHeader(e.getKey(), e.getValue());
  50. }
  51. return httpClient.execute(request);
  52. }
  53. /**
  54. * post form
  55. *
  56. * @param host
  57. * @param path
  58. * @param method
  59. * @param headers
  60. * @param querys
  61. * @param bodys
  62. * @return
  63. * @throws Exception
  64. */
  65. public static HttpResponse doPost(String host, String path, String method,
  66. Map<String, String> headers,
  67. Map<String, String> querys,
  68. Map<String, String> bodys)
  69. throws Exception {
  70. HttpClient httpClient = wrapClient(host);
  71. HttpPost request = new HttpPost(buildUrl(host, path, querys));
  72. for (Map.Entry<String, String> e : headers.entrySet()) {
  73. request.addHeader(e.getKey(), e.getValue());
  74. }
  75. if (bodys != null) {
  76. List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
  77. for (String key : bodys.keySet()) {
  78. nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
  79. }
  80. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
  81. formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
  82. request.setEntity(formEntity);
  83. }
  84. return httpClient.execute(request);
  85. }
  86. /**
  87. * Post String
  88. *
  89. * @param host
  90. * @param path
  91. * @param method
  92. * @param headers
  93. * @param querys
  94. * @param body
  95. * @return
  96. * @throws Exception
  97. */
  98. public static HttpResponse doPost(String host, String path, String method,
  99. Map<String, String> headers,
  100. Map<String, String> querys,
  101. String body)
  102. throws Exception {
  103. HttpClient httpClient = wrapClient(host);
  104. HttpPost request = new HttpPost(buildUrl(host, path, querys));
  105. for (Map.Entry<String, String> e : headers.entrySet()) {
  106. request.addHeader(e.getKey(), e.getValue());
  107. }
  108. if (StringUtils.isNotBlank(body)) {
  109. request.setEntity(new StringEntity(body, "utf-8"));
  110. }
  111. return httpClient.execute(request);
  112. }
  113. /**
  114. * Post stream
  115. *
  116. * @param host
  117. * @param path
  118. * @param method
  119. * @param headers
  120. * @param querys
  121. * @param body
  122. * @return
  123. * @throws Exception
  124. */
  125. public static HttpResponse doPost(String host, String path, String method,
  126. Map<String, String> headers,
  127. Map<String, String> querys,
  128. byte[] body)
  129. throws Exception {
  130. HttpClient httpClient = wrapClient(host);
  131. HttpPost request = new HttpPost(buildUrl(host, path, querys));
  132. for (Map.Entry<String, String> e : headers.entrySet()) {
  133. request.addHeader(e.getKey(), e.getValue());
  134. }
  135. if (body != null) {
  136. request.setEntity(new ByteArrayEntity(body));
  137. }
  138. return httpClient.execute(request);
  139. }
  140. /**
  141. * Put String
  142. * @param host
  143. * @param path
  144. * @param method
  145. * @param headers
  146. * @param querys
  147. * @param body
  148. * @return
  149. * @throws Exception
  150. */
  151. public static HttpResponse doPut(String host, String path, String method,
  152. Map<String, String> headers,
  153. Map<String, String> querys,
  154. String body)
  155. throws Exception {
  156. HttpClient httpClient = wrapClient(host);
  157. HttpPut request = new HttpPut(buildUrl(host, path, querys));
  158. for (Map.Entry<String, String> e : headers.entrySet()) {
  159. request.addHeader(e.getKey(), e.getValue());
  160. }
  161. if (StringUtils.isNotBlank(body)) {
  162. request.setEntity(new StringEntity(body, "utf-8"));
  163. }
  164. return httpClient.execute(request);
  165. }
  166. /**
  167. * Put stream
  168. * @param host
  169. * @param path
  170. * @param method
  171. * @param headers
  172. * @param querys
  173. * @param body
  174. * @return
  175. * @throws Exception
  176. */
  177. public static HttpResponse doPut(String host, String path, String method,
  178. Map<String, String> headers,
  179. Map<String, String> querys,
  180. byte[] body)
  181. throws Exception {
  182. HttpClient httpClient = wrapClient(host);
  183. HttpPut request = new HttpPut(buildUrl(host, path, querys));
  184. for (Map.Entry<String, String> e : headers.entrySet()) {
  185. request.addHeader(e.getKey(), e.getValue());
  186. }
  187. if (body != null) {
  188. request.setEntity(new ByteArrayEntity(body));
  189. }
  190. return httpClient.execute(request);
  191. }
  192. /**
  193. * Delete
  194. *
  195. * @param host
  196. * @param path
  197. * @param method
  198. * @param headers
  199. * @param querys
  200. * @return
  201. * @throws Exception
  202. */
  203. public static HttpResponse doDelete(String host, String path, String method,
  204. Map<String, String> headers,
  205. Map<String, String> querys)
  206. throws Exception {
  207. HttpClient httpClient = wrapClient(host);
  208. HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
  209. for (Map.Entry<String, String> e : headers.entrySet()) {
  210. request.addHeader(e.getKey(), e.getValue());
  211. }
  212. return httpClient.execute(request);
  213. }
  214. private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
  215. StringBuilder sbUrl = new StringBuilder();
  216. sbUrl.append(host);
  217. if (!StringUtils.isBlank(path)) {
  218. sbUrl.append(path);
  219. }
  220. if (null != querys) {
  221. StringBuilder sbQuery = new StringBuilder();
  222. for (Map.Entry<String, String> query : querys.entrySet()) {
  223. if (0 < sbQuery.length()) {
  224. sbQuery.append("&");
  225. }
  226. if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
  227. sbQuery.append(query.getValue());
  228. }
  229. if (!StringUtils.isBlank(query.getKey())) {
  230. sbQuery.append(query.getKey());
  231. if (!StringUtils.isBlank(query.getValue())) {
  232. sbQuery.append("=");
  233. sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
  234. }
  235. }
  236. }
  237. if (0 < sbQuery.length()) {
  238. sbUrl.append("?").append(sbQuery);
  239. }
  240. }
  241. return sbUrl.toString();
  242. }
  243. private static HttpClient wrapClient(String host) {
  244. HttpClient httpClient = new DefaultHttpClient();
  245. if (host.startsWith("https://")) {
  246. sslClient(httpClient);
  247. }
  248. return httpClient;
  249. }
  250. private static void sslClient(HttpClient httpClient) {
  251. try {
  252. SSLContext ctx = SSLContext.getInstance("TLS");
  253. X509TrustManager tm = new X509TrustManager() {
  254. public X509Certificate[] getAcceptedIssuers() {
  255. return null;
  256. }
  257. public void checkClientTrusted(X509Certificate[] xcs, String str) {
  258. }
  259. public void checkServerTrusted(X509Certificate[] xcs, String str) {
  260. }
  261. };
  262. ctx.init(null, new TrustManager[] { tm }, null);
  263. SSLSocketFactory ssf = new SSLSocketFactory(ctx);
  264. ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  265. ClientConnectionManager ccm = httpClient.getConnectionManager();
  266. SchemeRegistry registry = ccm.getSchemeRegistry();
  267. registry.register(new Scheme("https", 443, (SchemeSocketFactory) ssf));
  268. } catch (KeyManagementException ex) {
  269. throw new RuntimeException(ex);
  270. } catch (NoSuchAlgorithmException ex) {
  271. throw new RuntimeException(ex);
  272. }
  273. }
  274. }

controller

  1. @RestController
  2. @RequestMapping("api/user/sms")
  3. public class SmsController {
  4. @Resource
  5. private SmsService smsService ;
  6. @GetMapping(value = "/sendCode/{phone}")
  7. public Result sendValidateCode(@PathVariable String phone) {
  8. smsService.sendValidateCode(phone);
  9. return Result.build(null , ResultCodeEnum.SUCCESS) ;
  10. }
  11. }

servicesImpl

  1. import com.alibaba.nacos.common.utils.StringUtils;
  2. import com.atguigu.service.SmsService;
  3. import com.atguigu.utils.HttpUtils;
  4. import jakarta.annotation.Resource;
  5. import org.apache.commons.lang3.RandomStringUtils;
  6. import org.apache.http.HttpResponse;
  7. import org.springframework.data.redis.core.RedisTemplate;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. import java.util.concurrent.TimeUnit;
  11. public class SmsServiceImpl implements SmsService {
  12. @Resource
  13. private RedisTemplate<String,String> redisTemplate;
  14. @Override
  15. public void sendValidateCode(String phone) {
  16. String code = redisTemplate.opsForValue().get("phone:code:" + phone);
  17. if(StringUtils.hasText(code)) {
  18. return;
  19. }
  20. String validateCode = RandomStringUtils.randomNumeric(4); // 生成验证码
  21. redisTemplate.opsForValue().set("phone:code:" + phone , validateCode , 5 , TimeUnit.MINUTES);
  22. sendSms(phone , validateCode) ;
  23. }
  24. public void sendSms(String phone, String validateCode)
  25. {
  26. String host = "https://dfsns.market.alicloudapi.com";
  27. String path = "/data/send_sms";
  28. String method = "POST";
  29. String appcode = "你自己的AppCode";
  30. Map<String, String> headers = new HashMap<String, String>();
  31. //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
  32. headers.put("Authorization", "APPCODE " + appcode);
  33. //根据API的要求,定义相对应的Content-Type
  34. headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  35. Map<String, String> querys = new HashMap<String, String>();
  36. Map<String, String> bodys = new HashMap<String, String>();
  37. bodys.put("content", "code:"+validateCode);
  38. bodys.put("template_id", "CST_ptdie100"); //注意,CST_ptdie100该模板ID仅为调试使用,调试结果为"status": "OK" ,即表示接口调用成功,然后联系客服报备自己的专属签名模板ID,以保证短信稳定下发
  39. bodys.put("phone_number", phone);
  40. try {
  41. /**
  42. * 重要提示如下:
  43. * HttpUtils请从
  44. * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
  45. * 下载
  46. *
  47. * 相应的依赖请参照
  48. * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
  49. */
  50. HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
  51. System.out.println(response.toString());
  52. //获取response的body
  53. //System.out.println(EntityUtils.toString(response.getEntity()));
  54. } catch (Exception e) {
  55. e.printStackTrace();
  56. }
  57. }
  58. }

还需要导入mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC
        "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!-- 设置驼峰标识 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- 打印SQL语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <plugins>
        <!-- 分页插件 -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor"/>
    </plugins>
</configuration>

日志文件logback-spring.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration>
  3. <contextName>logback</contextName>
  4. <!-- 日志的输出目录 -->
  5. <property name="log.path" value="D://logs//spzx-manager//logs" />
  6. <!--控制台日志格式:彩色日志-->
  7. <!-- magenta:洋红 -->
  8. <!-- boldMagenta:粗红-->
  9. <!-- cyan:青色 -->
  10. <!-- white:白色 -->
  11. <!-- magenta:洋红 -->
  12. <property name="CONSOLE_LOG_PATTERN" value="%yellow(%date{yyyy-MM-dd HH:mm:ss}) %highlight([%-5level]) %green(%logger) %msg%n"/>
  13. <!--文件日志格式-->
  14. <property name="FILE_LOG_PATTERN" value="%date{yyyy-MM-dd HH:mm:ss} [%-5level] %thread %file:%line %logger %msg%n" />
  15. <!--编码-->
  16. <property name="ENCODING" value="UTF-8" />
  17. <!-- 控制台日志 -->
  18. <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
  19. <!-- 临界值过滤器 -->
  20. <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
  21. <level>INFO</level>
  22. </filter>
  23. <encoder>
  24. <pattern>${CONSOLE_LOG_PATTERN}</pattern>
  25. <charset>${ENCODING}</charset>
  26. </encoder>
  27. </appender>
  28. <!-- 文件日志 -->
  29. <appender name="FILE" class="ch.qos.logback.core.FileAppender">
  30. <file>${log.path}//log.log</file>
  31. <append>true</append>
  32. <encoder>
  33. <pattern>%date{yyyy-MM-dd HH:mm:ss} %msg%n</pattern>
  34. <charset>${ENCODING}</charset>
  35. </encoder>
  36. </appender>
  37. <!-- 开发环境 -->
  38. <springProfile name="dev">
  39. <!-- com.atguigu日志记录器:业务程序INFO级别 -->
  40. <logger name="com.atguigu" level="INFO" />
  41. <!-- 根日志记录器:INFO级别 -->
  42. <root level="INFO">
  43. <appender-ref ref="CONSOLE" />
  44. <appender-ref ref="FILE" />
  45. </root>
  46. </springProfile>
  47. </configuration>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/335998
推荐阅读
相关标签
  

闽ICP备14008679号