最近根据业务需要,要做一个客户根据小程序添加机器通过java同步到onenet平台上,写的不是很好,仅是自己记录功能的一个实现,需要做这块功能的可以参考下。
1.参考官方文档OneNET - 中国移动物联网开放平台
需要用到的一些依赖
<!-- onenet -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>bouncycastle</groupId>
<artifactId>bcprov-jdk15</artifactId>
<version>140</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<classifier>jdk15</classifier>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
java请求onenet平台的api需要鉴权认证,这里有两种鉴权方式:
1.通过onenet产品的 access_key和产品id外加一些参数,上代码
public static String assembleToken(String version, String resourceName, String expirationTime, String signatureMethod, String accessKey)
throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
StringBuilder sb = new StringBuilder();
String res = URLEncoder.encode(resourceName, "UTF-8");
String sig = URLEncoder.encode(generatorSignature(version, resourceName, expirationTime
, accessKey, signatureMethod), "UTF-8");
sb.append("version=")
.append(version)
.append("&res=")
.append(res)
.append("&et=")
.append(expirationTime)
.append("&method=")
.append(signatureMethod)
.append("&sign=")
.append(sig);
return sb.toString();
}
public static String generatorSignature(String version, String resourceName, String expirationTime, String accessKey, String signatureMethod)
throws NoSuchAlgorithmException, InvalidKeyException {
String encryptText = expirationTime + "\n" + signatureMethod + "\n" + resourceName + "\n" + version;
String signature;
byte[] bytes = HmacEncrypt(encryptText, accessKey, signatureMethod);
signature = Base64.getEncoder().encodeToString(bytes);
return signature;
}
public static byte[] HmacEncrypt(String data, String key, String signatureMethod)
throws NoSuchAlgorithmException, InvalidKeyException {
//根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
SecretKeySpec signinKey = null;
signinKey = new SecretKeySpec(Base64.getDecoder().decode(key),
"Hmac" + signatureMethod.toUpperCase());
//生成一个指定 Mac 算法 的 Mac 对象
Mac mac = null;
mac = Mac.getInstance("Hmac" + signatureMethod.toUpperCase());
//用给定密钥初始化 Mac 对象
mac.init(signinKey);
//完成 Mac 操作
return mac.doFinal(data.getBytes());
}
public enum SignatureMethod {
SHA1, MD5, SHA256;
}
public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
String version = "2018-10-31";
String resourceName = "products/503655";
String expirationTime = System.currentTimeMillis() / 1000 + 100 * 24 * 60 * 60 + "";
String signatureMethod = SignatureMethod.SHA1.name().toLowerCase();
String accessKey = "C1Rmf9T+8fj4B8JFCRpa+UTCKfhD3Sn8ImTLVepsT6I=";
String token = assembleToken(version, resourceName, expirationTime, signatureMethod, accessKey);
System.out.println("Authorization:" + token);
}
生成的token加在httpclient请求头上即可
2.请求头加上下面两个参数
"api-key", "SoTp=******************xeQ=" "Content-Type", "application/json"
这时候鉴权这一步通过,就可以调用api实现各种功能:这里我写的是不同的请求都有一个对应的请求类。
3.通过java请求增加设备api实现添加设备,需要配一个发送http请求的工具类
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 JSONObject 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPostHeader2(String url, JSONObject param)
{
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try
{
String urlNameString = url + "?" + param;
log.info("sendPost - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("api-key", "SoTp=UeADjqykplkhWE29UPWxeQ=");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null)
{
result.append(line);
}
log.info("recv - {}", result);
}
catch (ConnectException e)
{
log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
}
catch (SocketTimeoutException e)
{
log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
}
catch (IOException e)
{
log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
}
catch (Exception e)
{
log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
}
finally
{
try
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
接着写一个添加的测试方法
@Test
public void testAdd() {
JSONObject jsonOb = new JSONObject();
jsonOb.put("863318062144045", "112345678925");//imsi&imei
JSONObject object1 = new JSONObject();
object1.put("lon",100);//经度
object1.put("lat",25.31);//纬度
JSONObject jsonObject = new JSONObject();
jsonObject.put("protocol", "LWM2M");
jsonObject.put("device_id", "1018764821");
jsonObject.put("auth_info", jsonOb);
jsonObject.put("title", "test");
jsonObject.put("location",object1);
String url = "https://api.heclouds.com/devices";
System.out.println(jsonObject);
String sendPost = HttpUtils.sendPostHeader2(url, jsonObject);
JSONObject json = JSONObject.parseObject(sendPost);
if(json.get("errno").equals(0) && json.get("error").equals("succ")){
System.out.println(sendPost);
}
}
成功后返回:{"errno":0,"data":{"device_id":"1018835018","psk":"ADZPUiPzGoFWE0fh"},"error":"succ"}
4.修改onenet设备信息
修改的工具类 PUT请求
/**
* 原生字符串发送put请求
*
* @param url 请求的地址
* @param par 修改的产品id
* @param param 要修改的参数
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String doPut(String url, JSONObject param,String par) throws UnsupportedEncodingException {
String urlNameString = url + URLEncoder.encode(par,"UTF-8") + "?" + URLEncoder.encode(String.valueOf(param),"UTF-8");
log.info("sendPost - {}", urlNameString);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(urlNameString);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
httpPut.setConfig(requestConfig);
httpPut.setHeader("api-key", "SoTp=UeADjqykplkhWE29UPWxeQ=");
httpPut.setHeader("Content-type", "application/json");
httpPut.setHeader("DataEncoding", "UTF-8");
CloseableHttpResponse httpResponse = null;
try {
httpPut.setEntity(new StringEntity(String.valueOf(param), "UTF-8"));
httpResponse = httpClient.execute(httpPut);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
return result;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (httpResponse != null) {
try {
httpResponse.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
修改的测试代码
@Test
public void testUpdate() throws UnsupportedEncodingException {
String device_id = "1018849280";
JSONObject object1 = new JSONObject();
object1.put("lon",109);
object1.put("lat",23.54);
JSONObject object2 = new JSONObject();
object2.put("version","2.0.0");
object2.put("manufacturer","haha mobile");
JSONObject jsonObject = new JSONObject();
jsonObject.put("title", "test123");
jsonObject.put("desc", "desc");
jsonObject.put("location", object1);
jsonObject.put("other", object2);
String url = "http://api.heclouds.com/devices/";
System.out.println(jsonObject);
String sendPost = HttpUtils.doPut(url, jsonObject,device_id);
JSONObject json = JSONObject.parseObject(sendPost);
if(json.get("errno").equals(0) && json.get("error").equals("succ")){
System.out.println(sendPost);
}
}
成功后返回:{"errno":0, "error":"succ"}
5.删除设备信息的工具类
/**
* 向指定 URL 发送DELETE方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是
* @return 所代表远程资源的响应结果
*/
public static String sendDeleteHeader(String url, Long param)
{
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try
{
String urlNameString = url + param;
log.info("sendPost - {}", urlNameString);
URL realUrl = new URL(urlNameString);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
// conn.setConnectTimeout(5 * 1000);
// PUT请求
conn.setRequestMethod("DELETE");
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
// json格式上传的模式
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("api-key", "SoTp=UeADjqykplkhWE29UPWxeQ=");
conn.setRequestProperty("Content-Type", "application/json");
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null)
{
result.append(line);
}
log.info("recv - {}", result);
}
catch (ConnectException e)
{
log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
}
catch (SocketTimeoutException e)
{
log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
}
catch (IOException e)
{
log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
}
catch (Exception e)
{
log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
}
finally
{
try
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
删除的测试代码
@Test
public void testDelete() {
Long device_id = 1018857788L;
String url = "https://api.heclouds.com/devices/";
String sendPost = HttpUtils.sendDeleteHeader(url, device_id);
JSONObject json = JSONObject.parseObject(sendPost);
if(json.get("errno").equals(0) && json.get("error").equals("succ")){
System.out.println(sendPost);
}
}
成功后返回:{"errno":0, "error":"succ"}