Sample Java code for connecting a device to IoT Platform over HTTP.
IoT Platform supports device connections over HTTP (HTTPS connection).
This Java example covers request parameter configuration and device-side signature calculation for connecting to IoT Platform over HTTP.
Note HTTP connections are supported only in the China (Shanghai) regions.
pom.xml configuration
Add the following dependency to pom.xml to import the Alibaba fastjson package.
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
Sample code
The following code connects a device to IoT Platform over HTTP.
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;
/**
* A device connects to Alibaba Cloud IoT Platform over HTTP.
* For more information about the protocol specifications, see "HTTP Protocol Specifications".
* For more information about the data format, see "HTTPS Connection".
*/
public class IotHttpClient {
// The region ID. China (Shanghai) is used as an example.
private static String regionId = "cn-shanghai";
// The encryption method. The Message Authentication Code (MAC) algorithm can be HmacMD5 or HmacSHA1. The algorithm must be the same as the value of signmethod.
private static final String HMAC_ALGORITHM = "hmacsha1";
// The token is valid for 7 days. Obtain a new token after it expires.
private String token = null;
/**
* Initializes the HTTP client.
*
* @param productKey The product key.
* @param deviceName The device name.
* @param deviceSecret The device secret.
*/
public void conenct(String productKey, String deviceName, String deviceSecret) {
try {
// The registration 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);
// Get the output stream of the URLConnection object.
PrintWriter out = new PrintWriter(conn.getOutputStream());
// Send the request parameters.
out.print(authBody(productKey, deviceName, deviceSecret));
// Flush the buffer of the output stream.
out.flush();
// Get the input stream of the URLConnection object.
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// Read the response from the URL.
String result = "";
String line = "";
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println("----- auth result -----");
System.out.println(result);
// Close the input and output streams.
in.close();
out.close();
conn.disconnect();
// Get the token.
JSONObject json = JSONObject.parseObject(result);
if (json.getIntValue("code") == 0) {
token = json.getJSONObject("info").getString("token");
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Sends a message.
*
* @param topic The topic to which the message is sent.
* @param payload The message content.
*/
public void publish(String topic, byte[] payload) {
try {
// The registration 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);
// Get the output stream of the URLConnection object.
BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.write(payload);
out.flush();
// Get the input stream of the URLConnection object.
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// Read the response from the URL.
String result = "";
String line = "";
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println("----- publish result -----");
System.out.println(result);
// Close the input and output streams.
in.close();
out.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Generates the authentication request content.
*
* @param params The authentication parameters.
* @return The authentication request message body.
*/
private String authBody(String productKey, String deviceName, String deviceSecret) {
// Construct the authentication request.
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();
}
/**
* Signs the request on the device side.
*
* @param params The parameters to be signed.
* @param deviceSecret The device secret.
* @return The signature as a hexadecimal string.
*/
private String sign(JSONObject params, String deviceSecret) {
// Sort the request parameters in alphabetical order.
Set<String> keys = getSortedKeys(params);
// Exclude sign, signmethod, and version.
keys.remove("sign");
keys.remove("signmethod");
keys.remove("version");
// Assemble the plaintext for signing.
StringBuffer content = new StringBuffer();
for (String key : keys) {
content.append(key);
content.append(params.getString(key));
}
// Calculate the signature.
String sign = encrypt(content.toString(), deviceSecret);
System.out.println("sign content=" + content);
System.out.println("sign result=" + sign);
return sign;
}
/**
* Gets the sorted key set of a JSON object.
*
* @param json The JSON object to be sorted.
* @return The sorted key set.
*/
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();
}
/**
* Encrypts data using HMAC_ALGORITHM.
*
* @param content The plaintext.
* @param secret The key.
* @return The 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);
return byte2hex(mac.doFinal(text));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Converts a binary array to a hexadecimal string.
*
* @param b The binary array.
* @return The hexadecimal string.
*/
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);
// The topic to which the message is sent. Customize the topic in the console. The device must have the permission to publish messages to the topic.
String updateTopic = "/" + productKey + "/" + deviceName + "/user/update";
client.publish(updateTopic, "hello http".getBytes(StandardCharsets.UTF_8));
client.publish(updateTopic, new byte[] { 0x01, 0x02, 0x03 });
}
}