← 返回文档首页

☕ Java / Kotlin 对接

使用 HttpURLConnection + MessageDigest。

import java.io.*;
import java.net.*;
import java.security.MessageDigest;
import java.time.Instant;

public class LicenseClient {
    static final String API_BASE = "https://你的域名";
    static final String USERNAME = "你的用户名";
    static final String APP_NAME = "a";
    static final String APP_KEY  = "32位程序密钥";

    static String md5Sign(String act, String card, String mac, String app,
                          long ts, String key) throws Exception {
        String raw = act + "|" + card + "|" + mac + "|" + app + "|" + ts + "|" + key;
        byte[] digest = MessageDigest.getInstance("MD5").digest(raw.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) sb.append(String.format("%02x", b));
        return sb.toString();
    }

    static String call(String act, String card, String mac) throws Exception {
        long ts = Instant.now().getEpochSecond();
        String sign = md5Sign(act, card, mac, APP_NAME, ts, APP_KEY);
        String url = API_BASE + "/kami/" + USERNAME + "/check.php"
                + "?act=" + act + "&app=" + APP_NAME
                + "&card=" + URLEncoder.encode(card, "UTF-8")
                + "&mac=" + URLEncoder.encode(mac, "UTF-8")
                + "&sign=" + sign + "&ts=" + ts;
        HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
        c.setRequestMethod("GET");
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(c.getInputStream()))) {
            return br.lines().reduce("", String::concat);
        }
    }

    public static void main(String[] args) throws Exception {
        String card = "ABCD-EFGH-JKLM-NPQR";
        String mac  = "MACHINE-CODE";
        System.out.println(call("login", card, mac));
        while (true) {
            Thread.sleep(55_000);
            String r = call("heartbeat", card, mac);
            if (!r.contains("\"code\":0")) { System.out.println("心跳失败"); break; }
        }
    }
}