Step By Step
一.创建"地理位置"物模型
二.设备接入并获取token
三.发送HTTP请求
一.创建"地理位置"物模型
添加地理位置物模型属性,权限为读写。
二.设备接入并获取token
- 在pom.xml文件中,添加以下依赖,引入阿里fastjson包
- 进行设备认证以获取设备token、使用获取的token进行持续地数据上报
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.68</version></dependency>
packagejavasdk;/** Copyright © 2019 Alibaba. All rights reserved.*/importjava.io.BufferedOutputStream; importjava.io.BufferedReader; importjava.io.InputStreamReader; importjava.io.PrintWriter; importjava.net.URL; importjava.nio.charset.StandardCharsets; importjava.util.Set; importjava.util.SortedMap; importjava.util.TreeMap; importjavax.crypto.Mac; importjavax.crypto.spec.SecretKeySpec; importjavax.net.ssl.HttpsURLConnection; importcom.alibaba.fastjson.JSONObject; /*** 设备使用HTTP协议接入阿里云物联网平台。 * 协议规范说明,请参见《HTTP协议规范》。* 数据格式,请参见《HTTP连接通信》。*/publicclassIotHttpClient { // 地域ID,以华东2(上海)为例。privatestaticStringregionId="cn-shanghai"; // 定义加密方式,MAC算法可选以下算法:HmacMD5、HmacSHA1,需和signmethod一致。privatestaticfinalStringHMAC_ALGORITHM="hmacsha1"; // token有效期7天,失效后需要重新获取。privateStringtoken=null; /*** 初始化HTTP客户端。** @param productKey,产品key。* @param deviceName,设备名称。* @param deviceSecret,设备密钥。*/publicvoidconenct(StringproductKey, StringdeviceName, StringdeviceSecret) { try { // 注册地址。URLurl=newURL("https://iot-as-http."+regionId+".aliyuncs.com/auth"); HttpsURLConnectionconn= (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "application/json"); conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流。PrintWriterout=newPrintWriter(conn.getOutputStream()); // 发送请求参数。out.print(authBody(productKey, deviceName, deviceSecret)); // flush输出流的缓冲。out.flush(); // 获取URLConnection对象对应的输入流。BufferedReaderin=newBufferedReader(newInputStreamReader(conn.getInputStream())); // 读取URL的响应。Stringresult=""; Stringline=""; while ((line=in.readLine()) !=null) { result+=line; } System.out.println("----- auth result -----"); System.out.println(result); // 关闭输入输出流。in.close(); out.close(); conn.disconnect(); // 获取token。JSONObjectjson=JSONObject.parseObject(result); if (json.getIntValue("code") ==0) { token=json.getJSONObject("info").getString("token"); } } catch (Exceptione) { e.printStackTrace(); } } privateStringauthBody(StringproductKey, StringdeviceName, StringdeviceSecret) { // 构建认证请求。JSONObjectbody=newJSONObject(); 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()); returnbody.toJSONString(); } /*** 设备端签名。** @param params,签名参数。* @param deviceSecret,设备密钥。* @return 签名十六进制字符串。*/privateStringsign(JSONObjectparams, StringdeviceSecret) { // 请求参数按字典顺序排序。Set<String>keys=getSortedKeys(params); // sign、signmethod和version除外。keys.remove("sign"); keys.remove("signmethod"); keys.remove("version"); // 组装签名明文。StringBuffercontent=newStringBuffer(); for (Stringkey : keys) { content.append(key); content.append(params.getString(key)); } // 计算签名。Stringsign=encrypt(content.toString(), deviceSecret); System.out.println("sign content="+content); System.out.println("sign result="+sign); returnsign; } /*** 获取JSON对象排序后的key集合。** @param json,需要排序的JSON对象。* @return 排序后的key集合。*/privateSet<String>getSortedKeys(JSONObjectjson) { SortedMap<String, String>map=newTreeMap<String, String>(); for (Stringkey : json.keySet()) { Stringvlaue=json.getString(key); map.put(key, vlaue); } returnmap.keySet(); } /*** 使用HMAC_ALGORITHM加密。** @param content,明文。* @param secret,密钥。* @return 密文。*/privateStringencrypt(Stringcontent, Stringsecret) { try { byte[] text=content.getBytes(StandardCharsets.UTF_8); byte[] key=secret.getBytes(StandardCharsets.UTF_8); SecretKeySpecsecretKey=newSecretKeySpec(key, HMAC_ALGORITHM); Macmac=Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); returnbyte2hex(mac.doFinal(text)); } catch (Exceptione) { e.printStackTrace(); returnnull; } } /*** 二进制转十六进制字符串。** @param b,二进制数组。* @return 十六进制字符串。*/privateStringbyte2hex(byte[] b) { StringBuffersb=newStringBuffer(); for (intn=0; b!=null&&n<b.length; n++) { Stringstmp=Integer.toHexString(b[n] &0XFF); if (stmp.length() ==1) { sb.append('0'); } sb.append(stmp); } returnsb.toString().toUpperCase(); } publicstaticvoidmain(String[] args) { StringproductKey=""; StringdeviceName=""; StringdeviceSecret=""; IotHttpClientclient=newIotHttpClient(); client.conenct(productKey, deviceName, deviceSecret); } }
三.发送HTTP请求
本文以IPV4定位展示
Topic: /sys/"+productKey+"/"+deviceName+"/_thing/service/post
Payload: {"id":"123","version":"1.0","params":{"identifier":"Location.Position","serviceParams":{"type":"ip","ip":"10.1.1.1"}},"method":"_thing.service.post"}
/*** 发送消息。** @param topic,发送消息的Topic。* @param payload,消息内容。*/publicvoidpublish(Stringtopic, byte[] payload) { try { // 注册地址。URLurl=newURL("https://iot-as-http."+regionId+".aliyuncs.com/topic"+topic); HttpsURLConnectionconn= (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "application/octet-stream"); conn.setRequestProperty("password", token); conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流。BufferedOutputStreamout=newBufferedOutputStream(conn.getOutputStream()); out.write(payload); out.flush(); // 获取URLConnection对象对应的输入流。BufferedReaderin=newBufferedReader(newInputStreamReader(conn.getInputStream())); // 读取URL的响应。Stringresult=""; Stringline=""; while ((line=in.readLine()) !=null) { result+=line; } System.out.println("----- publish result -----"); System.out.println(result); // 关闭输入输出流。in.close(); out.close(); conn.disconnect(); } catch (Exceptione) { e.printStackTrace(); } }
参考文档