1.购买aliyun免费短信(限购)
测试一下,真要买的话有点贵
点击购买
进入然后可以找到AppCode有用
点击接口进入文档
找到java复制粘贴导入jar包 输入手机号即可
官方代码()
public static void main(String[] args) {
String host = "https://dfsns.market.alicloudapi.com";
String path = "/data/send_sms";
String method = "POST";
String appcode = "你自己的AppCode";
Map<String, String> headers = new HashMap<String, String>();
//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);
//根据API的要求,定义相对应的Content-Type
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
Map<String, String> querys = new HashMap<String, String>();
Map<String, String> bodys = new HashMap<String, String>();
bodys.put("content", "code:1234");
bodys.put("template_id", "CST_ptdie100");
bodys.put("phone_number", "156*****140");
try {
/**
* 重要提示如下:
* HttpUtils请从
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
* 下载
*
* 相应的依赖请参照
* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
*/
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();
}
}
2. 使用hutool工具包
自己的话其实简单修改一下也行,因为懒得找上方的依赖,而且主要内容就是发送post请求,所以就使用
hutool工具包
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.18</version>
</dependency>
代码
public String send(String phone){
//短信好通过前端发送过来
String url = "https://dfsns.market.alicloudapi.com/data/send_sms";
String appcode = "用自己的";
//码随机生成
int code = RandomUtil.randomInt(1000,9999);
HttpRequest request = HttpRequest.of(url).method(Method.POST)
.header("Authorization", "APPCODE " + appcode)
.body((StrUtil.format("content=code:{}&template_id=CST_ptdie100&phone_number={}",code, phone)));
HttpResponse response = request.execute();
int statusCode = response.getStatus();
String body = response.body();
//返回值就是成功与否,在官网能看到
return statusCode + body;
}
需要用到自己的