← 短信API

用 Java 发送短信

本教程介绍如何使用 NS SMS API 从 Java 发送短信。短信从你自己的 Android 手机和 SIM 卡发出,因此没有按条费用,也无需注册发送方。大约需要五分钟。

准备工作

无需账号、邮箱或密码。手机会自动注册,并在应用中直接显示 API 密钥。

第 1 步:用 Java 发送短信

用 POST 提交国际格式的收件人号码(E.164,例如 +14155550123)和短信内容。API 返回 202 Accepted 和消息 ID。

SendSms.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class SendSms {
    public static void main(String[] args) throws Exception {
        String json = """
            {"device_id":"%s","to":"+14155550123","text":"Your code is 4821"}
            """.formatted(System.getenv("NS_SMS_DEVICE_ID"));
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://sms-api.n-soft.pl/v1/sms/send"))
            .header("Authorization", "Bearer " + System.getenv("NS_SMS_API_KEY"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(json))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient()
            .send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode() + " " + response.body());
    }
}

第 2 步:查询送达状态

GET /v1/sms/{id} 返回当前状态:手机已接收、已发送、已送达,或失败并附错误代码。状态通常在几秒内更新。

GET /v1/sms/{id}
GET https://sms-api.n-soft.pl/v1/sms/01JDX4K8Q2M3N4P5R6S7T8V9W0
Authorization: Bearer $NS_SMS_API_KEY

{"id":"01JDX4K8Q2M3N4P5R6S7T8V9W0","status":"delivered","error_code":null,
 "sent_at":"2026-11-26T10:58:30+00:00","delivered_at":"2026-11-26T10:58:31+00:00", ...}

第 3 步:接收状态 Webhook(可选)

在所有套餐中,服务器都会把每次状态变化 POST 到你的 Webhook。信任请求之前,请先校验签名:

webhook
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class WebhookSignature {
    public static boolean isValid(byte[] body, String header, String secret) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        String expected = "sha256=" + HexFormat.of().formatHex(mac.doFinal(body));
        return MessageDigest.isEqual(
            expected.getBytes(StandardCharsets.UTF_8),
            header.getBytes(StandardCharsets.UTF_8));
    }
}

第 4 步:定时发送短信

在同一请求中添加 send_at 即可在指定时间发送,添加 repeat 即可每天、每周或每月发送:

POST /v1/sms/send
{
  "device_id": "01JDX4K8Q2M3N4P5R6S7T8V9W0",
  "to": "+14155550123",
  "text": "Reminder: your appointment is tomorrow at 10:00",
  "send_at": "2026-12-01T09:00:00+01:00",
  "repeat": { "every": "weekly", "count": 4 }
}

其他语言的同一短信API