package com.nq.utils.sms;
|
|
import com.nq.utils.PropertiesUtil;
|
import org.apache.commons.lang3.StringUtils;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
|
import java.io.BufferedReader;
|
import java.io.InputStream;
|
import java.io.InputStreamReader;
|
import java.net.HttpURLConnection;
|
import java.net.URL;
|
import java.net.URLEncoder;
|
import java.nio.charset.StandardCharsets;
|
|
public final class SmsBaoClient {
|
|
private static final Logger log = LoggerFactory.getLogger(SmsBaoClient.class);
|
|
private static final String API_URL = "https://api.smsbao.com/sms";
|
|
private SmsBaoClient() {
|
}
|
|
/**
|
* @return true 发送成功(返回码 0)
|
*/
|
public static boolean send(String phone, String content) {
|
String username = PropertiesUtil.getProperty("smsbao.username");
|
String apiKey = PropertiesUtil.getProperty("smsbao.apikey");
|
if (StringUtils.isBlank(username) || StringUtils.isBlank(apiKey)) {
|
log.error("短信宝配置缺失 smsbao.username / smsbao.apikey");
|
return false;
|
}
|
try {
|
String encodedContent = URLEncoder.encode(content, StandardCharsets.UTF_8.name());
|
String httpArg = "u=" + username
|
+ "&p=" + apiKey
|
+ "&m=" + phone
|
+ "&c=" + encodedContent;
|
String result = request(API_URL, httpArg);
|
if ("0".equals(StringUtils.trimToEmpty(result))) {
|
return true;
|
}
|
log.error("短信宝发送失败 phone={} result={} msg={}", phone, result, mapError(result));
|
return false;
|
} catch (Exception e) {
|
log.error("短信宝发送异常 phone=" + phone, e);
|
return false;
|
}
|
}
|
|
private static String request(String httpUrl, String httpArg) throws Exception {
|
String fullUrl = httpUrl + "?" + httpArg;
|
URL url = new URL(fullUrl);
|
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
connection.setRequestMethod("GET");
|
connection.setConnectTimeout(10000);
|
connection.setReadTimeout(10000);
|
connection.connect();
|
try (InputStream is = connection.getInputStream();
|
BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
|
StringBuilder sbf = new StringBuilder();
|
String line;
|
while ((line = reader.readLine()) != null) {
|
sbf.append(line);
|
}
|
return sbf.toString();
|
}
|
}
|
|
private static String mapError(String code) {
|
if (code == null) {
|
return "未知错误";
|
}
|
switch (code.trim()) {
|
case "30":
|
return "错误密码";
|
case "40":
|
return "账号不存在";
|
case "41":
|
return "余额不足";
|
case "43":
|
return "IP地址限制";
|
case "50":
|
return "内容含有敏感词";
|
case "51":
|
return "手机号码不正确";
|
default:
|
return "错误码:" + code;
|
}
|
}
|
}
|