すべてのプロダクト
Search
ドキュメントセンター

IoT Platform:HTTP 経由での IoT Platform への接続

最終更新日:Jun 11, 2026

HTTP 経由でデバイスを IoT Platform に接続するための Java サンプルコードです。

IoT Platform は、HTTP 経由のデバイス接続 (HTTPS 接続) をサポートしています。

この Java サンプルでは、HTTP 経由で IoT Platform に接続するためのリクエストパラメーターの構成と、デバイス側の署名計算について説明します。

説明 HTTP 接続は、中国 (上海) リージョンでのみサポートされています。

pom.xml の構成

Alibaba fastjson パッケージをインポートするには、次の依存関係を pom.xml に追加します。

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.83</version>
</dependency>

サンプルコード

次のコードは、HTTP 経由でデバイスを IoT Platform に接続します。

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;

import com.alibaba.fastjson.JSONObject;

/**
 * HTTP 経由でデバイスを Alibaba Cloud IoT Platform に接続します。
 * プロトコル仕様の詳細については、「HTTP Protocol Specifications」をご参照ください。
 * データ形式の詳細については、「HTTPS Connection」をご参照ください。
 */
public class IotHttpClient {

    // リージョン ID。ここでは中国 (上海) を例にしています。
    private static String regionId = "cn-shanghai";

    // 暗号化方式。メッセージ認証コード (MAC) アルゴリズムは HmacMD5 または HmacSHA1 を使用できます。アルゴリズムは signmethod の値と同じである必要があります。
    private static final String HMAC_ALGORITHM = "hmacsha1";

    // トークンの有効期間は 7 日間です。有効期限が切れたら新しいトークンを取得します。
    private String token = null;

    /**
     * HTTPクライアントを初期化します。
     * 
     * @param productKey プロダクトキー。
     * @param deviceName デバイス名。
     * @param deviceSecret デバイスシークレット。
     */
    public void conenct(String productKey, String deviceName, String deviceSecret) {
        try {
            // 登録URL。
            URL url = new URL("https://iot-as-http." + regionId + ".aliyuncs.com/auth");

            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-type", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            // URLConnection オブジェクトの出力ストリームを取得します。
            PrintWriter out = new PrintWriter(conn.getOutputStream());
            // リクエストパラメーターを送信します。
            out.print(authBody(productKey, deviceName, deviceSecret));
            // 出力ストリームのバッファーをフラッシュします。
            out.flush();

            // URLConnection オブジェクトの入力ストリームを取得します。
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            // URL からのレスポンスを読み取ります。
            String result = "";
            String line = "";
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println("----- auth result -----");
            System.out.println(result);

            // 入力ストリームと出力ストリームを閉じます。
            in.close();
            out.close();
            conn.disconnect();

            // トークンを取得します。
            JSONObject json = JSONObject.parseObject(result);
            if (json.getIntValue("code") == 0) {
                token = json.getJSONObject("info").getString("token");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * メッセージをパブリッシュします。
     * 
     * @param topic メッセージのパブリッシュ先トピック。
     * @param payload メッセージ本文。
     */
    public void publish(String topic, byte[] payload) {
        try {
            // パブリッシュURL。
            URL url = new URL("https://iot-as-http." + regionId + ".aliyuncs.com/topic" + topic);

            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-type", "application/octet-stream");
            conn.setRequestProperty("password", token);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            // URLConnection オブジェクトの出力ストリームを取得します。
            BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());
            out.write(payload);
            out.flush();

            // URLConnection オブジェクトの入力ストリームを取得します。
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            // URL からのレスポンスを読み取ります。
            String result = "";
            String line = "";
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println("----- publish result -----");
            System.out.println(result);

            // 入力ストリームと出力ストリームを閉じます。
            in.close();
            out.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 認証リクエストの内容を生成します。
     * 
     * @param params 認証パラメーター。
     * @return 認証リクエストのメッセージ本文。
     */
    private String authBody(String productKey, String deviceName, String deviceSecret) {

        // 認証リクエストを構築します。
        JSONObject body = new JSONObject();
        body.put("productKey", productKey);
        body.put("deviceName", deviceName);
        body.put("clientId", productKey + "." + deviceName);
        body.put("timestamp", String.valueOf(System.currentTimeMillis()));
        body.put("signmethod", HMAC_ALGORITHM);
        body.put("version", "default");
        body.put("sign", sign(body, deviceSecret));

        System.out.println("----- auth body -----");
        System.out.println(body.toJSONString());

        return body.toJSONString();
    }

    /**
     * デバイス側でリクエストに署名します。
     * 
     * @param params 署名対象のパラメーター。
     * @param deviceSecret デバイスシークレット。
     * @return 16 進数文字列形式の署名。
     */
    private String sign(JSONObject params, String deviceSecret) {

        // リクエストパラメーターをアルファベット順にソートします。
        Set<String> keys = getSortedKeys(params);

        // sign、signmethod、version を除外します。
        keys.remove("sign");
        keys.remove("signmethod");
        keys.remove("version");

        // 署名用のプレーンテキストを組み立てます。
        StringBuffer content = new StringBuffer();
        for (String key : keys) {
            content.append(key);
            content.append(params.getString(key));
        }

        // 署名を計算します。
        String sign = encrypt(content.toString(), deviceSecret);
        System.out.println("sign content=" + content);
        System.out.println("sign result=" + sign);

        return sign;
    }

    /**
     * JSON オブジェクトのソート済みキーセットを取得します。
     * 
     * @param json ソート対象のJSONオブジェクト。
     * @return ソート済みキーセット。
     */
    private Set<String> getSortedKeys(JSONObject json) {
        SortedMap<String, String> map = new TreeMap<String, String>();
        for (String key : json.keySet()) {
            String value = json.getString(key);
            map.put(key, value);
        }
        return map.keySet();
    }

    /**
     * HMAC_ALGORITHM を使用してデータを暗号化します。
     * 
     * @param content プレーンテキスト。
     * @param secret キー。
     * @return 暗号文。
     */
    private String encrypt(String content, String secret) {
        try {
            byte[] text = content.getBytes(StandardCharsets.UTF_8);
            byte[] key = secret.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec secretKey = new SecretKeySpec(key, HMAC_ALGORITHM);
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            return byte2hex(mac.doFinal(text));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * バイナリ配列を 16 進数文字列に変換します。
     * 
     * @param b バイナリ配列。
     * @return 16 進数文字列。
     */
    private String byte2hex(byte[] b) {
        StringBuffer sb = new StringBuffer();
        for (int n = 0; b != null && n < b.length; n++) {
            String stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1) {
                sb.append('0');
            }
            sb.append(stmp);
        }
        return sb.toString().toUpperCase();
    }

    public static void main(String[] args) {
        String productKey = "your-productKey";
        String deviceName = "your-deviceName";
        String deviceSecret = "your-deviceSecret";
        IotHttpClient client = new IotHttpClient();
        client.conenct(productKey, deviceName, deviceSecret);
        // メッセージの送信先トピック。コンソールでトピックをカスタマイズします。デバイスには、トピックにメッセージをパブリッシュする権限が必要です。
        String updateTopic = "/" + productKey + "/" + deviceName + "/user/update";
        client.publish(updateTopic, "hello http".getBytes(StandardCharsets.UTF_8));
        client.publish(updateTopic, new byte[] { 0x01, 0x02, 0x03 });
    }
}