下载源码
使用git从远程下载验证码服务代码(开源)。
git clone https://github.com/fightingape/sailing.git
如果redis有密码的话:需要在克隆的配置文件中修改自己redis的密码
1.3.3 开通腾讯云短信服务
本服务中的短信发送使用了腾讯云短信服务,生产环境需要注册腾讯云开通短信服务:
1)开通腾讯云短信服务
https://cloud.tencent.com/product/isms/getting-started
获得验证码
我们在swagger中来测试接口
然后进行验证:
同时在后台可以看到打印出验证码
验证验证码:
1. 接口说明:http://localhost:56085/sailing/swagger-ui.html#/verification-controller/verifyUsingPOST
verficationCode 就是我们要发送的验证码,verificationKey是我们获得验证码时,同时收到的key
所以我么你自己的项目需调用短信服务的接口,我们用okHttp,因为性能比较好
restTemplate简单入门
在自己的调用服务中:
<!-- okhttp3依赖 -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
因为我在我的父工程中指定了版本,所以在我的调用中没有指定版本,我父工程中的引来是:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.9.1</version>
</dependency>
restTemplate 的bean指定用okhttp的实现方式:
@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class RestTemplateTest {
@Autowired
RestTemplate restTemplate;
// 测试使用restTemplate作为http的客户端,向http服务端发起请求
@Test
public void getHtml() {
String url = "http://www.baidu.com/";
ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
String body = forEntity.getBody();
System.out.println(body);
}
}
用ok3http 出现乱码,我们需要在restTemplate的bean中进行修改:即修改我们前面注册的restTemplate 的bean的方法
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
//消息转换器列表
List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
//配置消息转换器StringHttpMessageConverter,并设置utf-8
// 在索引的为1的位置重新设置字符编码原因:restTemplate有转换器列表,在位置为1的位置是string类型的,可以自己打断点,查看
messageConverters.set(1,
new StringHttpMessageConverter(StandardCharsets.UTF_8));//支持中文字符集,默认ISO-8859-1,支持utf-8
return restTemplate;
}
请求验证码:
// 向短信服务发送请求获取验证码
@Test
public void getSmsCode() {
String url = "http://localhost:56085/sailing/generate?name=sms&effectiveTime=600";//验证码过期时间为600秒
// http 的请求信息,需要在header中指出用是传递的json格式,需要在body中存对应的数据
// 设置请求体
Map<String, Object> body = new HashMap<>();
body.put("mobile", "1234"); // 发送对应的手机号
// 设置请求头部
HttpHeaders headers = new HttpHeaders();
//设置发送的类型:Content-Type: application/json
headers.setContentType(MediaType.APPLICATION_JSON);
// 填充请求的信息
HttpEntity httpEntity = new HttpEntity(body, headers);
// 请求urlnexchage是restTemplate请求POST方式的方法, 第四个参数:map,表示将收到的数据转化为map
ResponseEntity<Map> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);
log.info("请求验证码的服务.得到响应:{} ", JSON.toJSONString(exchange));
Map resultMap = exchange.getBody();
Map result = (Map) resultMap.get("result");
String smsKey = (String)result.get("key");
log.info(smsKey);
}