@GetMapping("/phone/send/code")
@ApiOperation(value = "发送短信验证码", notes = "发送短信验证码 的详细描述")
public Result sendCode(@RequestParam("phone") String phone) {
if (!CommonUtil.checkPhone(phone)) return Result.fail("手机号码格式错误");
if (userService.queryByPhone(phone) != null) return Result.fail("手机号码已注册");
// post请求 参数用query
String host = "https://gyytz.market.alicloudapi.com/sms/smsSend";
// 密钥
String appcode = "你的密钥";
// 短信模板 网上有模板
String templateId = "a09602b817fd47e59e7c6e603d3f088d";
// 短信前缀 例如:【阿里云】
String smsSignId = "2e65b1bb3d054466b82f0c9d125465e2";
// 验证码:1234 2分钟内有效
String param = "**code**:1234,**minute**:2";
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建http POST请求
HttpPost httpPost = new HttpPost(host);
// 请求头
httpPost.setHeader("Authorization", "APPCODE " + appcode);
//#region 请求体
List<NameValuePair> querys = new ArrayList<>();
querys.add(new BasicNameValuePair("mobile", phone));
querys.add(new BasicNameValuePair("templateId", templateId));
querys.add(new BasicNameValuePair("smsSignId", smsSignId));
querys.add(new BasicNameValuePair("param", param));
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity;
try {
formEntity = new UrlEncodedFormEntity(querys);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
httpPost.setEntity(formEntity);
//#endregion
CloseableHttpResponse response = null;
try {
// 执行请求
response = httpclient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
// 自定义返回状态码
if (jsonObject.getIntValue("code") == 0) {
// 发送成功
return Result.success("短信已发送,2分钟内有效,请注意查收!");
} else {
return Result.fail("短信发送失败:" + jsonObject.getString("msg"));
}
} else {
return Result.fail(response.getStatusLine().getReasonPhrase());
}
} catch (IOException e) {
return Result.fail("短信发送失败:" + e.getMessage());
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
try {
httpclient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
HttpClient发送短信案例
最新推荐文章于 2024-01-17 21:20:29 发布