安卓原生与 NleCloud 通信最简封装

2 minute read

直接上代码

  1package moe.ibox.httpurlconnection;
  2
  3import android.support.annotation.NonNull;
  4import android.support.annotation.Nullable;
  5import android.support.v7.app.AppCompatActivity;
  6import android.os.Bundle;
  7import android.util.Log;
  8
  9import org.json.JSONException;
 10import org.json.JSONObject;
 11
 12import java.io.BufferedReader;
 13import java.io.IOException;
 14import java.io.InputStream;
 15import java.io.InputStreamReader;
 16import java.io.OutputStream;
 17import java.net.HttpURLConnection;
 18import java.net.URL;
 19import java.nio.charset.StandardCharsets;
 20
 21public class MainActivity extends AppCompatActivity {
 22
 23    String BASE_URL = "https://api.nlecloud.com";
 24    String ACCESS_TOKEN = "";
 25
 26    @Override
 27    protected void onCreate(Bundle savedInstanceState) {
 28        super.onCreate(savedInstanceState);
 29        setContentView(R.layout.activity_main);
 30
 31        new Thread(() -> {
 32            try {
 33                /* POST /Users/Login 用户登录 */
 34                JSONObject loginObject = new JSONObject(httpRequest(
 35                        "POST",
 36                        "/Users/Login",
 37                        "Account=15223348149&Password=hrn96596",
 38                        null,
 39                        null
 40                ));
 41                JSONObject loginResultObject = loginObject.optJSONObject("ResultObj");
 42                assert loginResultObject != null;
 43                ACCESS_TOKEN = loginResultObject.optString("AccessToken");
 44                Log.i("ACCESS_TOKEN", ACCESS_TOKEN);
 45                /* POST /Cmds 设备命令控制 */
 46                Log.i("CONTROL", httpRequest(
 47                        "POST",
 48                        "/Cmds?deviceId=439317&apiTag=fs",
 49                        "1",
 50                        "application/json",
 51                        ACCESS_TOKEN
 52                ));
 53                /* GET /devices 传感器数据获取 */
 54                Log.i("QuerySensor", String.valueOf(readSensorValue(httpRequest(
 55                        "GET",
 56                        "/devices/439317/sensors/z_temperature",
 57                        null,
 58                        null,
 59                        ACCESS_TOKEN
 60                ))));
 61            } catch (JSONException e) {
 62                e.printStackTrace();
 63            }
 64        }).start();
 65    }
 66
 67    /**
 68     * @param method      请求方法
 69     * @param uri         API 路径
 70     * @param body        请求体
 71     * @param contentType 请求头(Header)的内容类型
 72     * @param token       Access Token
 73     * @return 响应内容(Body)
 74     */
 75    @NonNull
 76    private String httpRequest(String method, String uri, @Nullable String body, @Nullable String contentType, @Nullable String token) {
 77        try {
 78            URL url = new URL(BASE_URL + uri);
 79            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 80            connection.setRequestMethod(method);
 81            if (contentType != null) connection.addRequestProperty("Content-Type", contentType);
 82            if (token != null) connection.addRequestProperty("AccessToken", token);
 83            if (body != null) {
 84                OutputStream outputStream = connection.getOutputStream();
 85                outputStream.write(body.getBytes(StandardCharsets.UTF_8));
 86            }
 87            return is2str(connection.getInputStream());
 88        } catch (IOException e) {
 89            e.printStackTrace();
 90            return "";
 91        }
 92    }
 93
 94    /**
 95     * @param inputStream 输入流
 96     * @return 从输入流中读取的内容转换的字符串
 97     */
 98    @NonNull
 99    private String is2str(InputStream inputStream) {
100        try {
101            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
102            StringBuilder stringBuilder = new StringBuilder();
103            String line;
104            while ((line = reader.readLine()) != null) {
105                stringBuilder.append(line).append("\n");
106            }
107            inputStream.close();
108            reader.close();
109            return stringBuilder.toString();
110        } catch (IOException e) {
111            e.printStackTrace();
112            return "";
113        }
114    }
115
116    /**
117     * @param response 响应内容
118     * @return 传感器值
119     */
120    private double readSensorValue(String response) {
121        try {
122            JSONObject jsonObject = new JSONObject(response);
123            JSONObject resultObj = jsonObject.optJSONObject("ResultObj");
124            assert resultObj != null;
125            return resultObj.optDouble("Value");
126        } catch (JSONException e) {
127            e.printStackTrace();
128            return -1;
129        }
130    }
131}