android与OneNET云平台的获取数据与发送数据

这篇文章对于大学学生来说应该是一个福利,因为可能跟你的毕业设计相关联。
1.GET 获取云平台的数据

private static final String DeviceID = "715410157";
    private static final String ApiKey = "=0nEsfHhq5sfImFv4oQYGHv=wDg=";
    private static final String humistream = "humistream";//onenet平台上对应设备的其中一个数据流的名字
    private static final String tempstream = "tempstream";


 public void Get() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient clientHumi = new OkHttpClient();
                    Request requestHumi = new Request.Builder().url("https://api.heclouds.com/devices/" + DeviceID + "/datapoints?datastream_id=" + humistream).header("api-key", ApiKey).build();
                    Response responseHumi = clientHumi.newCall(requestHumi).execute();
                    String responseHumiData = responseHumi.body().string();


                    parseJSONWithGSONHumi(responseHumiData);

                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    OkHttpClient clientTemp = new OkHttpClient();
                    Request requestTemp = new Request.Builder().url("https://api.heclouds.com/devices/" + DeviceID + "/datapoints?datastream_id=" + tempstream).header("api-key", ApiKey).build();
                    Response responseTemp = clientTemp.newCall(requestTemp).execute();
                    String responseTempData = responseTemp.body().string();

                    parseJSONWithGSONTemp(responseTempData);

                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    OkHttpClient clientAir = new OkHttpClient();
                    Request requestAir = new Request.Builder().url("https://api.heclouds.com/devices/" + DeviceID + "/datapoints?datastream_id=" + airQuality).header("api-key", ApiKey).build();
                    Response responseAir = clientAir.newCall(requestAir).execute();
                    String responseAirData = responseAir.body().string();

                    parseJSONWithGSONAir(responseAirData);

                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    OkHttpClient clientLight = new OkHttpClient();
                    Request requestLight = new Request.Builder().url("https://api.heclouds.com/devices/" + DeviceID + "/datapoints?datastream_id=" + lightIntensities).header("api-key", ApiKey).build();
                    Response responseLight = clientLight.newCall(requestLight).execute();
                    String responseLightData = responseLight.body().string();

                    parseJSONWithGSONLight(responseLightData);

                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }).start();

    }

想要获取正常的数据格式还需要数据解析,从云平台发下来的是json格式
接下来创建四个工具类
1.

```java
public class Data {
    private int count;
    private List<Datastreams> datastreams;
    public void setCount(int count) {
        this.count = count;
    }
    public int getCount() {
        return count;
    }

    public void setDatastreams(List<Datastreams> datastreams) {
        this.datastreams = datastreams;
    }
    public List<Datastreams> getDatastreams() {
        return datastreams;
    }

}
public class Datapoints {
    private String at;
    private String value;


    public void setvValue(String value) {
        this.value = value;
    }

    public String getAt() {
        return at;
    }

    public void setAt(String at) {
        this.at = at;
    }

    public String getValue() {
        return value;
    }

}
public class Datastreams {
    private List<Datapoints> datapoints;
    private String id;
    public void setDatapoints(List<Datapoints> datapoints) {
        this.datapoints = datapoints;
    }
    public List<Datapoints> getDatapoints() {
        return datapoints;
    }

    public void setId(String id) {
        this.id = id;
    }
    public String getId() {
        return id;
    }


}
public class JsonRootBean {
    private int errno;
    private Data data;
    private String error;
    public void setErrno(int errno) {
        this.errno = errno;
    }
    public int getErrno() {
        return errno;
    }

    public void setData(Data data) {
        this.data = data;
    }
    public Data getData() {
        return data;
    }

    public void setError(String error) {
        this.error = error;
    }
    public String getError() {
        return error;
    }

}

private void parseJSONWithGSONAir(String jsonData) {
        JsonRootBean app = new Gson().fromJson(jsonData, JsonRootBean.class);
        List<Datastreams> streams = app.getData().getDatastreams();
        List<Datapoints> points = streams.get(0).getDatapoints();
        int count = app.getData().getCount();//获取数据的数量
        for (int i = 0; i < points.size(); i++) {
            String air = points.get(i).getValue();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                //下面是你需要展示数据界面的操作,不要什么都不想,直接复制,我之所以发这篇文章是想,如果你对安卓确实不熟悉,可以给你帮助,但如果你想了解安卓或从事相关行业,那应该以后抽时间把它看懂。
                    airQualityData.setText(air);
                    if (Integer.parseInt(air.toString().trim()) > 65) {
                        airQualityData.setTextColor(Color.parseColor("#ff2400"));
                    } else if (Integer.parseInt(air.toString()) < 45) {
                        airQualityData.setTextColor(Color.parseColor("#238e23"));
                    } else {
                        airQualityData.setTextColor(Color.parseColor("#7f7f7f"));
                    }
                }
            });

        }

    }


对于上面的参数我不会跟你说,因为你能够搜索到这篇文章说明,说明你应该对上面的参数熟悉,而且我的参数命名已经很清楚了。

2.发送数据到云平台(这里是发送数据不是发送命令)

private fun sendLight(id: String, value: Boolean) {
        Thread {
            //
            var connection: HttpURLConnection? = null
            var reader: BufferedReader? = null
            try {
            //这里的724410117是你的设备号
                val url = URL("https://api.heclouds.com/devices/724410117/datapoints")
                connection = url.openConnection() as HttpURLConnection

                //connection.setRequestMethod("GET");//如需使用post方式,注释本行,释放下面三行
                //POST方式,传递数据
                connection.connectTimeout = 5000
                connection!!.doOutput = true
                connection.doInput = true
                connection.requestMethod = "POST"
                connection.useCaches = false
                val data =
                    "{\"datastreams\": [{\"id\":\"" + id + "\",\"datapoints\": [{\"value\":" +
                            value + "}]}]}"

                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded ")
                connection.setRequestProperty("Content-Len", data.length.toString() + "")
                connection.setRequestProperty("api-key", ApiKey)
                connection.readTimeout = 8000
                //                    DataOutputStream data1 = new DataOutputStream(connection.getOutputStream());
                val pw = PrintWriter(connection.outputStream)
                pw.print(data)
                pw.flush()
                pw.close()

                val inputStream = connection.inputStream //获取服务器返回输入流
                reader = BufferedReader(InputStreamReader(inputStream))
                val response = StringBuilder()
                var line: String?
                while (reader.readLine().also { line = it } != null) {
                    response.append(line)
                }

            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                if (reader != null) {
                    try {
                        reader.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
                connection?.disconnect()
            }
        }.start()
    }

这里你通过调用sendLight方法传入数据流的名称和值就好了。
其他的问题可以点击下面的链接去查看官方文档
云平台文档中心

  • 15
    点赞
  • 101
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

橘子先生z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值