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

IoT Platform:HTTPを使用したIoT Platformへのアクセス

最終更新日:Apr 17, 2025

このトピックでは、HTTPを使用してデバイスをIoT Platformに接続する方法について説明します。

HTTPを使用してデバイスをIoT Platformに接続できます。 詳細については、「HTTPSによる接続の確立」をご参照ください。

このトピックでは、デバイスSDK for Javaに基づいて開発されたサンプルコードを使用して、デバイスをIoT Platformに接続します。 connectioinを確立する前に、要求パラメータやデバイスの証明書情報など、必要なパラメータを指定する必要があります。

説明 この機能は、中国 (上海) リージョンでのみ使用できます。

pom.xmlファイルの設定

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

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

サンプルコード

次のコードは、デバイスをIoT Platformに接続し、データ通信を有効にする方法を示しています。

java.io.BufferedOutputStreamをインポートします。java.io.BufferedReaderをインポートします。java.io.InputStreamReaderをインポートします。java.io.PrintWriterをインポートします。impor t java.net.URL;
java.nio.charset.StandardCharsetsをインポートします。java.util.Setをインポートします。java.util.SortedMapをインポートします。java.util.TreeMapをインポートします。javax.crypto.Macをインポートします。javax.crypto.spec.SecretKeySpecをインポートします。impor t javax.net.ssl.HttpsURLConnection;

com.alibaba.fastjson.JSONObjectをインポートします。/**
 * HTTPを使用してデバイスをIoT Platformに接続します。 
 * HTTPプロトコルの詳細については、「HTTP標準」をご参照ください。
 * データ形式の詳細については、「HTTPによる接続の確立」を参照してください。
 * /
パブリッククラスIotHttpClient {

    // リージョンのID。 利用可能なリージョンは中国 (上海) のみです。
    プライベート静的文字列regionId = "cn-shanghai";

    // 暗号化アルゴリズムを指定します。 HMAC_ALGORITHMパラメーターをhmacsha1またはhmacmd5に設定します。 設定する値は、signmethodパラメーターの値と同じである必要があります。
    プライベート静的最終文字列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("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()));
            // エンドポイントから応答を取得します。
            String result = "";
            文字列ライン="";
            while (((line = in.readLine())) != null) {
                結果 +=ライン;
            }
            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トピックメッセージの送信先のトピック。
     * @ param payloadメッセージの内容。
     */
    public void publish(String topic, byte[] payload) {
        try {
            // メッセージの送信先のトピックのエンドポイントを指定します。
            URL url=新しい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" 、トークン);
            conn.setDoOutput(true);
            conn.setDoInput(true);

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

            // URLConnectionオブジェクトの入力ストリームを取得します。
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            // エンドポイントから応答を取得します。
            String result = "";
            文字列ライン="";
            while (((line = in.readLine())) != null) {
                結果 +=ライン;
            }
            System.out.println("----- publish result -----");
            System.out.println(result);

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

    /**
     * 認証に必要なパラメータを生成します。
     * 
     * @ param params認証に必要なパラメーター。
     * @ return認証要求を含むメッセージ。
     */
    プライベートString authBody(String productKey, String deviceName, String deviceSecret) {

        // 認証リクエストを作成します。
        JSONObjectボディ=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進形式の署名。
     */
    プライベート文字列記号 (JSONObject params, String deviceSecret) {

        // リクエストパラメータをalphbetical順序で並べ替えます。
        <String> keys = getSortedKeys(params) を設定します。

        // sign、signmethod、およびversionパラメーターを削除します。
        キー削除 ("sign");
        keys.remove("signmethod");
        keys.remove("version");

        // 署名の平文を取得する
        StringBuffer content = new StringBuffer();
        for (String key : keys) {
            content.append (キー);
            content.append(params.getString (キー));
        }

        // 署名を生成する
        String sign = encrypt(content.toString(), deviceSecret);
        System.out.println("sign content=" + content);
        System.out.println("sign result=" + sign);

        リターンサイン;
    }

    /**
     * JSONオブジェクトをキーと値のペアのセットに変換します。
     * 
     * @ param json変換されるJSONオブジェクト。
     * @ return JSONオブジェクトから変換されたキーと値のペアのセット。
     */
    プライベートセット <String> getSortedKeys(JSONObject json) {
        SortedMap<String, String> map = new TreeMap<String, String>();
        for (文字列キー: json.keySet()) {
            文字列値=json.getString (キー);
            map.put (キー、値);
        }
        リターンmap.keySet();
    }

    /**
     * HMAC_ALGORITHMパラメーターで暗号化方法を指定します。
     * 
     * @ paramコンテンツ平文。
     * @ param secret暗号化キー。
     * @ return Ciphertext。
     */
    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);
            byte2hexを返します (mac.doFinal (テキスト)) 。
        } catch (Exception e) {
            e.printStackTrace();
            ヌルを返します。
        }
    }

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

    public static void main(String[] args) {
        String productKey = "お使いのデバイスのproductKey";
        String deviceName = "デバイスのdeviceName";
        String deviceSecret = "デバイスのdeviceSecret";
        IotHttpClient client = new IotHttpClient();
        client.conenct(productKey, deviceName, deviceSecret);
        // メッセージの送信先のトピック。 IoT Platformコンソールで、カスタムトピックを作成し、デバイスにパブリッシュ権限を付与できます。
        文字列updateTopic = "/" + productKey + "/" + deviceName + "/user/update";
        client.publish(updateTopic, "hello http".getBytes(StandardCharsets.UTF_8));
        client.publish(updateTopic, new byte[] { 0x01, 0x02, 0x03 });
    }
}