隨業務全球化拓展,短信驗證碼、國際短信群發成為標配需求。本文提供基於雲片(YunPian)短信平台的 Java 完整實現,涵蓋賬戶查詢、智能匹配模板發送、指定模板發送、語音驗證碼、主被叫綁定/解綁等核心接口,代碼開箱即用,並解析關鍵設計要點。
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
基於 Apache HttpClient 4.3+ 實現 HTTP POST 請求,統一 UTF-8 編碼。
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.*;
public class JavaSmsApi {
// 接口端點
private static final String URI_GET_USER_INFO = "https://sms.yunpian.com/v2/user/get.json";
private static final String URI_SEND_SMS = "https://sms.yunpian.com/v2/sms/single_send.json";
private static final String URI_TPL_SEND_SMS = "https://sms.yunpian.com/v2/sms/tpl_single_send.json";
private static final String URI_SEND_VOICE = "https://voice.yunpian.com/v2/voice/send.json";
private static final String URI_SEND_BIND = "https://call.yunpian.com/v2/call/bind.json";
private static final String URI_SEND_UNBIND = "https://call.yunpian.com/v2/call/unbind.json";
private static final String ENCODING = "UTF-8";
/** 通用 POST 方法 */
public static String post(String url, Map<String, String> paramsMap) {
CloseableHttpClient client = HttpClients.createDefault();
String responseText = "";
CloseableHttpResponse response = null;
try {
HttpPost method = new HttpPost(url);
if (paramsMap != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (Map.Entry<String, String> param : paramsMap.entrySet()) {
paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
}
response = client.execute(method);
HttpEntity entity = response.getEntity();
if (entity != null) {
responseText = EntityUtils.toString(entity, ENCODING);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (response != null) response.close(); } catch (Exception ignored) {}
}
return responseText;
}
// ========== 業務接口 ==========
/** 查賬戶信息 */
public static String getUserInfo(String apikey) throws IOException, URISyntaxException {
Map<String, String> params = new HashMap<>();
params.put("apikey", apikey);
return post(URI_GET_USER_INFO, params);
}
/** 智能匹配模板發送(推薦) */
public static String sendSms(String apikey, String text, String mobile) throws IOException {
Map<String, String> params = new HashMap<>();
params.put("apikey", apikey);
params.put("text", text); // 內容需與已審核模板匹配
params.put("mobile", mobile);
return post(URI_SEND_SMS, params);
}
/** 指定模板發送 */
public static String tplSendSms(String apikey, long tplId, String tplValue, String mobile) throws IOException {
Map<String, String> params = new HashMap<>();
params.put("apikey", apikey);
params.put("tpl_id", String.valueOf(tplId));
params.put("tpl_value", tplValue); // URLEncoder 編碼後的鍵值對
params.put("mobile", mobile);
return post(URI_TPL_SEND_SMS, params);
}
/** 語音驗證碼 */
public static String sendVoice(String apikey, String mobile, String code) {
Map<String, String> params = new HashMap<>();
params.put("apikey", apikey);
params.put("mobile", mobile);
params.put("code", code);
return post(URI_SEND_VOICE, params);
}
/** 綁定主被叫 */
public static String bindCall(String apikey, String from, String to, Integer duration) {
Map<String, String> params = new HashMap<>();
params.put("apikey", apikey);
params.put("from", from);
params.put("to", to);
params.put("duration", String.valueOf(duration));
return post(URI_SEND_BIND, params);
}
/** 解綁主被叫 */
public static String unbindCall(String apikey, String from, String to) {
Map<String, String> params = new HashMap<>();
params.put("apikey", apikey);
params.put("from", from);
params.put("to", to);
return post(URI_SEND_UNBIND, params);
}
// ========== 測試主方法 ==========
public static void main(String[] args) throws Exception {
String apikey = "xxxxxxxxxxxxxxxxxxxxx"; // 替換為你的 apikey
String mobile = "130xxxxxxxx"; // 替換為目標手機號
// 1. 查賬戶
System.out.println("賬戶信息: " + getUserInfo(apikey));
// 2. 智能匹配發送(推薦)
String text = "【雲片網】您的驗證碼是1234";
// System.out.println("智能發送: " + sendSms(apikey, text, mobile));
// 3. 指定模板發送
long tplId = 1; // 模板 ID
String tplValue = URLEncoder.encode("#code#", ENCODING) + "=" + URLEncoder.encode("1234", ENCODING)
+ "&" + URLEncoder.encode("#company#", ENCODING) + "=" + URLEncoder.encode("雲片網", ENCODING);
System.out.println("模板變量: " + tplValue);
System.out.println("模板發送: " + tplSendSms(apikey, tplId, tplValue, mobile));
// 4. 語音驗證碼
// System.out.println("語音驗證碼: " + sendVoice(apikey, mobile, "1234"));
// 5. 綁定/解綁示例
// String from = "+86130xxxxxxxx";
// String to = "+86131xxxxxxxx";
// System.out.println("綁定: " + bindCall(apikey, from, to, 30 * 60));
// System.out.println("解綁: " + unbindCall(apikey, from, to));
}
}
tpl_id + tpl_value,需自行 URLEncoder 編碼變量值,靈活但維護成本高。雲片國際短信**複用相同接口**,只需:
+346xxxxxxxx 西班牙)。// 建議擴展:指數退避重試 + 熔斷 + 異步發送
public String sendWithRetry(String apikey, String text, String mobile, int maxRetry) {
for (int i = 0; i < maxRetry; i++) {
String resp = sendSms(apikey, text, mobile);
if (isSuccess(resp)) return resp;
sleep((long) Math.pow(2, i) * 100); // 100ms, 200ms, 400ms...
}
// 記錄失敗日志、進入補發隊列
return "FAILED";
}
@Async("smsExecutor")
public CompletableFuture<String> sendAsync(String apikey, String text, String mobile) {
return CompletableFuture.supplyAsync(() -> {
try { return sendSms(apikey, text, mobile); }
catch (IOException e) { throw new CompletionException(e); }
});
}
// 監控指標:發送成功率、平均耗時、失敗碼分布、積壓隊列長度
基於雲片 API 的 Java 短信發送實現核心在於:
短信業務看似簡單,實則關係用戶體驗、安全合規與系統穩定。建議將發送邏輯封裝為獨立微服務/模組,統一接入網關、限流、審計,避免分散在各業務代碼中難以治理。