移动物联网M5310-A上手-未完

2019-03-12  本文已影响0人  fitsir

M5310-A物联网模块

移动物联网开发板—NB版

连接OneNet平台

Qt连接OneNet平台

Android连接OneNet平台

使用HttpUrlConnectionPost方法发送Json格式数据

  1. json格式数据
            JSONObject body = new JSONObject();
            JSONObject LBS = new JSONObject();
            Double lon = deviceLocation.getLongitude();
            Double lat = deviceLocation.getLatitude();

            try {
                LBS.put("lon", lon);
                LBS.put("lat", lat);
                body.put("LBS", LBS);
                Message msg = mhandler.obtainMessage();
                msg.what = 1;
                msg.obj = body.toString();
                mhandler.sendMessage(msg);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            String content = String.valueOf(body);

content内容为{"LBS": {"lon": lon, "lat": lat}}

  1. 发送POST
            String target = "http://api.heclouds.com/devices/" + deviceID + "/datapoints?type=3";
            URL url;
            try {
                url = new URL(target);
                HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                urlConn.setRequestMethod("POST");
                urlConn.setDoOutput(true);
                urlConn.setDoInput(true);
                urlConn.setUseCaches(false);
                urlConn.setInstanceFollowRedirects(true);
                urlConn.setRequestProperty("Content-Type", "application/json");
                urlConn.setRequestProperty("accept", "application/json");
                urlConn.setRequestProperty("api-key", "应用的APIKEY");
                urlConn.connect();
                //发送数据
                OutputStream out = new DataOutputStream(urlConn.getOutputStream());
                out.write(content.getBytes());
                out.flush();
                out.close();

                //接收
                InputStreamReader in = new InputStreamReader(urlConn.getInputStream()); // 获得读取的内容
                BufferedReader buffer = new BufferedReader(in); // 获取输入流对象
                String inputLine = null;
                String response_result = "";
                while ((inputLine = buffer.readLine()) != null) {  //通过循环逐行读取输入流中的内容
                    response_result += inputLine;

                }
                Message msg0 = mhandler.obtainMessage();
                msg0.what = 0;
                msg0.obj = response_result;
                mhandler.sendMessage(msg0);


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
上一篇下一篇

猜你喜欢

热点阅读