我的:
(1)代码:
package com.test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.security.MessageDigest;
import java.util.Base64;
/**
* @description 短信发送
*/
@Component
public class SmsUtils {
@Value("${sms.url}")
private String smsUrl;
@Autowired
RestTemplate restTemplate;
/**
* 根据手机号给手机发验证码
*/
public boolean send(SmsBO bo) {
try {
//请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 请求体
bo.setMobiles("15626299333");
HttpEntity<SmsBO> httpEntity = new HttpEntity<>(bo, headers);
// 发送请求
ResponseEntity<String> response = restTemplate.postForEntity(smsUrl, httpEntity, String.class);
// 返回
String body = response.getBody();
System.out.println(body);
JSONObject jsonBody = JSON.parseObject(body);
Boolean flag = jsonBody.getBoolean("success");
return flag;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
// base64加密
private static String toBase64(String str) throws Exception{
return Base64.getEncoder().encodeToString(str.getBytes("utf8"));
}
// 转为 32位 小写的 MD5摘要
private static String toMd5(String str) throws Exception {
return encryptMode(str, "MD5");
}
// 转为 安全哈希算法 SHA
private static String toSha(String str) throws Exception {
return encryptMode(str, "SHA");
}
/**
* 加密
* @param str
* @param model "MD5"、"SHA"、"SHA1"、"SHA-224".....
*/
private static String encryptMode(String str, String model) throws Exception {
MessageDigest md = MessageDigest.getInstance(model);
// 更新
md.update(str.getBytes("utf8"));
// 获取
byte[] bt = md.digest();
// 转换
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < bt.length; i++) {
buffer.append(Character.forDigit((bt[i] & 240) >> 4, 16));
buffer.append(Character.forDigit(bt[i] & 15, 16));
}
return buffer.toString();
}
}