Android从OceanConnect上获取数据

Android从OceanConnect上获取数据_第1张图片

接口文档下载:https://developer.huawei.com/ict/cn/rescenter/CMDA_FIELD_OCEAN_CONNECT?developlan=Other

主要看第九章

第一步:Auth(鉴权),获取accessToken。

调用方法
POST
接口路径
https://server:port/iocm/app/sec/v1.1.0/login

Android从OceanConnect上获取数据_第2张图片

Android从OceanConnect上获取数据_第3张图片

Android从OceanConnect上获取数据_第4张图片

public class MainActivity extends Activity {
    private static HttpClient httpClient;
    String appId = Constant.APPID;
    String secret = Constant.SECRET;
    String urlLogin = Constant.APP_AUTH;
    String urldatahistory=Constant.QUERY_DEVICE_HISTORY_DATA;
    String deviceId = "aa6a1a7e-c4a7-40e2-a0aa-cb96302b153c";
    String gatewayId="aa6a1a7e-c4a7-40e2-a0aa-cb96302b153c";
    String serviceId="S1";
    String accessToken;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        

        new Thread(new Runnable() {
            @Override
            public void run() {
                try
                {
                    cert();

                }

                catch (Exception e)
                {
                    Log.d("MainActivity", "++++++++++++++++");
                }
            }
        }).start();


}


    public void cert() throws Exception
    {

        // 服务器端需要验证的客户端证书
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        // 客户端信任的服务器端证书
        KeyStore trustStore = KeyStore.getInstance("BKS");

        InputStream ksIn = getApplicationContext().getAssets().open(Constant.SELFCERTPATH);
        InputStream tsIn = getApplicationContext().getAssets().open(Constant.TRUSTCAPATH);
        try {
            keyStore.load(ksIn, Constant.SELFCERTPWD.toCharArray());
            trustStore.load(tsIn, Constant.TRUSTCAPWD.toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ksIn.close();
            } catch (Exception ignore) {
            }
            try {
                tsIn.close();
            } catch (Exception ignore) {
            }
        }

//        SSLContext sc = SSLContext.getInstance("TLS");
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("X509");
        keyManagerFactory.init(keyStore, Constant.SELFCERTPWD.toCharArray());
//        sc.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        SSLSocketFactory ssl = new SSLSocketFactory(keyStore, Constant.SELFCERTPWD, trustStore);
        ssl.setHostnameVerifier(new AllowAllHostnameVerifier());
//        ssl.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
        httpClient = new DefaultHttpClient();
        if (ssl != null) {
            Scheme sch = new Scheme("https", ssl, 443);   //从这里开始研究
            httpClient.getConnectionManager().getSchemeRegistry().register(sch);
        }
        Map param = new HashMap<>();
        param.put("appId", appId);
        param.put("secret", secret);

        List nvps = new LinkedList();
        Set> paramsSet = param.entrySet();
        for (Map.Entry paramEntry : paramsSet) {
            nvps.add(new BasicNameValuePair(paramEntry.getKey(), paramEntry
                    .getValue()));
        }
        HttpPost request = new HttpPost(urlLogin);

        request.setEntity(new UrlEncodedFormEntity(nvps));
        //get accessToken
        HttpResponse response = executeHttpRequest(request);

    }

    //get accessToken
    private HttpResponse executeHttpRequest(HttpUriRequest request) {
        HttpResponse response = null;
        String result = "ERROR";
        try {
            response = httpClient.execute(request);
        } catch (Exception e) {
            System.out.println("executeHttpRequest failed.");
        } finally {
            if (response.getStatusLine().getStatusCode() == 200)
            {
                try {
                    result= convertStreamToString(response.getEntity().getContent());
          
                    parseJSONWithGSON(result);
                 
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
            else
            {
                try {
                    Log.e(TAG , "CommonPostWithJson | response error | "
                            + response.getStatusLine().getStatusCode()
                            + " error :"
                            + EntityUtils.toString(response.getEntity()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
//            try {
//                System.out.println("aaa  ==  response -> " + response);
//                HttpEntity entity = response.getEntity();
//
//            } catch (Exception e) {
//                System.out.println("IOException: " + e.getMessage());
//            }
        }

        return response;
    }

    
   


    //解析accessToken
    private void parseJSONWithGSON(String jsonData) {
        try
        {
           
            JSONObject jsonObject = new JSONObject(jsonData);
            accessToken = jsonObject.getString("accessToken");
            accessToken = accessToken.trim();
            

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



    public static String convertStreamToString(InputStream is) {
        /*
          * To convert the InputStream to String we use the BufferedReader.readLine()
          * method. We iterate until the BufferedReader return null which means
          * there's no more data to read. Each line will appended to a StringBuilder
          * and returned as String.
          */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

第二步:查询设备历史数据

调用方法
GET
接口路径
https://server:port/iocm/app/data/v1.1.0/deviceDataHistory?deviceId={deviceId}&
gatewayId={gatewayId}&serviceId ={serviceId}&pageNo={pageNo}&pageSize
={pageSize}&startTime={startTime}&endTime={endTime}&property={property}&appId={appId}

官方api文档中有{},但我觉得{}要去掉。

注意事项
携带头域信息 
Header:
"app_key:{appId}" 
"Authorization:Bearer {accessToken}" 
Content-Type:application/json;

Android从OceanConnect上获取数据_第5张图片

返回结果

Android从OceanConnect上获取数据_第6张图片

Android从OceanConnect上获取数据_第7张图片

Android从OceanConnect上获取数据_第8张图片

Android从OceanConnect上获取数据_第9张图片

Android从OceanConnect上获取数据_第10张图片

public class MainActivity extends Activity {
    private static HttpClient httpClient;
    String appId = Constant.APPID;
    String secret = Constant.SECRET;
    String urlLogin = Constant.APP_AUTH;
    String urldatahistory=Constant.QUERY_DEVICE_HISTORY_DATA;
    String deviceId = "aa6a1a7e-c4a7-40e2-a0aa-cb96302b153c";
    String gatewayId="aa6a1a7e-c4a7-40e2-a0aa-cb96302b153c";
    String serviceId="S1";
    String accessToken;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        new Thread(new Runnable() {
            @Override
            public void run() {
                try
                {
                    cert();

                }

                catch (Exception e)
                {
                    Log.d("MainActivity", "++++++++++++++++");
                }
            }
        }).start();


}


    public void cert() throws Exception
    {

        // 服务器端需要验证的客户端证书
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        // 客户端信任的服务器端证书
        KeyStore trustStore = KeyStore.getInstance("BKS");

        InputStream ksIn = getApplicationContext().getAssets().open(Constant.SELFCERTPATH);
        InputStream tsIn = getApplicationContext().getAssets().open(Constant.TRUSTCAPATH);
        try {
            keyStore.load(ksIn, Constant.SELFCERTPWD.toCharArray());
            trustStore.load(tsIn, Constant.TRUSTCAPWD.toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ksIn.close();
            } catch (Exception ignore) {
            }
            try {
                tsIn.close();
            } catch (Exception ignore) {
            }
        }

//        SSLContext sc = SSLContext.getInstance("TLS");
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("X509");
        keyManagerFactory.init(keyStore, Constant.SELFCERTPWD.toCharArray());
//        sc.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        SSLSocketFactory ssl = new SSLSocketFactory(keyStore, Constant.SELFCERTPWD, trustStore);
        ssl.setHostnameVerifier(new AllowAllHostnameVerifier());
//        ssl.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
        httpClient = new DefaultHttpClient();
        if (ssl != null) {
            Scheme sch = new Scheme("https", ssl, 443);   //从这里开始研究
            httpClient.getConnectionManager().getSchemeRegistry().register(sch);
        }
        Map param = new HashMap<>();
        param.put("appId", appId);
        param.put("secret", secret);

        List nvps = new LinkedList();
        Set> paramsSet = param.entrySet();
        for (Map.Entry paramEntry : paramsSet) {
            nvps.add(new BasicNameValuePair(paramEntry.getKey(), paramEntry
                    .getValue()));
        }
        HttpPost request = new HttpPost(urlLogin);

        request.setEntity(new UrlEncodedFormEntity(nvps));
        //get accessToken
        HttpResponse response = executeHttpRequest(request);

    }

    //get accessToken
    private HttpResponse executeHttpRequest(HttpUriRequest request) {
        HttpResponse response = null;
        String result = "ERROR";
        try {
            response = httpClient.execute(request);
        } catch (Exception e) {
            System.out.println("executeHttpRequest failed.");
        } finally {
            if (response.getStatusLine().getStatusCode() == 200)
            {
                try {
                    result= convertStreamToString(response.getEntity().getContent());

                    parseJSONWithGSON(result);
            

                    //get数据和时间
                    runHttpsOkHttp();

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


            }
            else
            {
                try {
                    Log.e(TAG , "CommonPostWithJson | response error | "
                            + response.getStatusLine().getStatusCode()
                            + " error :"
                            + EntityUtils.toString(response.getEntity()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
//            try {
//                System.out.println("aaa  ==  response -> " + response);
//                HttpEntity entity = response.getEntity();
//
//            } catch (Exception e) {
//                System.out.println("IOException: " + e.getMessage());
//            }
        }

        return response;
    }

    //get数据和时间
    private void runHttpsOkHttp() {
        try {
            // 服务器端需要验证的客户端证书
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            // 客户端信任的服务器端证书
            KeyStore trustStore = KeyStore.getInstance("BKS");

            InputStream ksIn = getApplicationContext().getAssets().open(Constant.SELFCERTPATH);
            InputStream tsIn = getApplicationContext().getAssets().open(Constant.TRUSTCAPATH);
            try {
                keyStore.load(ksIn, Constant.SELFCERTPWD.toCharArray());
                trustStore.load(tsIn, Constant.TRUSTCAPWD.toCharArray());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    ksIn.close();
                } catch (Exception ignore) {
                }
                try {
                    tsIn.close();
                } catch (Exception ignore) {
                }
            }

            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(trustStore);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("X509");
            keyManagerFactory.init(keyStore, Constant.SELFCERTPWD.toCharArray());


            SSLSocketFactory ssl = new SSLSocketFactory(keyStore, Constant.SELFCERTPWD, trustStore);
            ssl.setHostnameVerifier(new AllowAllHostnameVerifier());




            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

            final HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    //不校验服务器端证书域名
                    return true;
                }
            };

            OkHttpClient mOkHttpClient = new OkHttpClient().newBuilder().hostnameVerifier(hostnameVerifier)
                    .sslSocketFactory(sc.getSocketFactory()).build();
//            RequestBody requestBodyPost = new FormBody.Builder()
//                    .add("appId", Constant.APPID)
//                    .add("secret", Constant.SECRET)
//                    .add("refreshToken","123")
//                    .build();
            Request request = null;

                request = new Request.Builder()
                        .url(urldatahistory + "?deviceId="+deviceId +
                                "&gatewayId=" +gatewayId+
                                "&serviceId="+serviceId)//2018/11/11 16:10:10  和实际相差8个小时  20181111T150000Z  2018/11/11 23:00:00 ? 获取11/11那天的数据 20181111T081000Z
                        .addHeader("app_key", appId)
                        .addHeader("Authorization", "Bearer " + accessToken)
                        .addHeader("Content-Type", "application/json")
                        .build();

            Call call = mOkHttpClient.newCall(request);

            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {


                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String str = response.body().string();
                    Log.d("a",str);
                    parseJSONWithGSON2(str);


                }
            });

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


    //解析accessToken
    private void parseJSONWithGSON(String jsonData) {
        try
        {
            //app = new Gson().fromJson(jsonData, JsonRootBean.class);
            JSONObject jsonObject = new JSONObject(jsonData);
            accessToken = jsonObject.getString("accessToken");
            accessToken = accessToken.trim();
            Log.d("a", accessToken);

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

    //解析数据和时间
    private void parseJSONWithGSON2(String jsonData) {
        try
        {
       /*     app2 = new Gson().fromJson(jsonData, JsonRootBean2.class);
            List deviceDataHistoryDTOs = app2.getDeviceDataHistoryDTOs();
            for(int i=0;i

build.gradle 在android下添加

useLibrary 'org.apache.http.legacy'
public class Constant {

    //please replace the IP and Port, when you use the demo.
    public static final String BASE_URL = "https://139.159.133.59:8743";

    //please replace the appId and secret, when you use the demo.
    public static final String APPID = "raEQYhAjaEfD_dilBarKtYFIqiQa";
    public static final String SECRET = "fDb7_xwtykd6N43pRg6XsMJNvzMa";

    /*
     *IP and port of callback url.
     *please replace the IP and Port of your Application deployment environment address, when you use the demo.
     */
    public static final String CALLBACK_BASE_URL = "http://192.88.88.88:9999";

    /*
     * complete callback url锛�
     * please replace uri, when you use the demo.
     */
    public static final String DEVICE_ADDED_CALLBACK_URL = CALLBACK_BASE_URL + "/na/iocm/devNotify/v1.1.0/addDevice";
    public static final String DEVICE_INFO_CHANGED_CALLBACK_URL = CALLBACK_BASE_URL + "/na/iocm/devNotify/v1.1.0/updateDeviceInfo";
    public static final String DEVICE_DATA_CHANGED_CALLBACK_URL = CALLBACK_BASE_URL + "/na/iocm/devNotify/v1.1.0/updateDeviceData";
    public static final String DEVICE_DELETED_CALLBACK_URL = CALLBACK_BASE_URL + "/na/iocm/devNotify/v1.1.0/deletedDevice";
    public static final String MESSAGE_CONFIRM_CALLBACK_URL = CALLBACK_BASE_URL + "/na/iocm/devNotify/v1.1.0/commandConfirmData";
    public static final String SERVICE_INFO_CHANGED_CALLBACK_URL = CALLBACK_BASE_URL + "/na/iocm/devNotify/v1.1.0/updateServiceInfo";
    public static final String COMMAND_RSP_CALLBACK_URL = CALLBACK_BASE_URL + "/na/iocm/devNotify/v1.1.0/commandRspData";
    public static final String DEVICE_EVENT_CALLBACK_URL = CALLBACK_BASE_URL + "/na/iocm/devNotify/v1.1.0/DeviceEvent";
    public static final String RULE_EVENT_CALLBACK_URL = CALLBACK_BASE_URL + "/na/iocm/devNotify/v1.1.0/RulEevent";
    public static final String DEVICE_DATAS_CHANGED_CALLBACK_URL = CALLBACK_BASE_URL + "/na/iocm/devNotify/v1.1.0/updateDeviceDatas";


    /*
     * Specifies the callback URL for the command execution result notification.
     * For details about the execution result notification definition.
     *
     * please replace uri, when you use the demo.
     */
    public static final String REPORT_CMD_EXEC_RESULT_CALLBACK_URL = CALLBACK_BASE_URL + "/na/iocm/devNotify/v1.1.0/reportCmdExecResult";


    //Paths of certificates.
//    public static String SELFCERTPATH = "/src/resource/cert/outgoing.CertwithKey.pkcs12";
//    public static String TRUSTCAPATH = "/src/resource/cert/ca.jks";

    public static String SELFCERTPATH = "outgoing.CertwithKey.pkcs12";
    public static String TRUSTCAPATH = "ca.bks";


    //Password of certificates.
    public static String SELFCERTPWD = "IoM@1234";
    public static String TRUSTCAPWD = "123456";






    //*************************** The following constants do not need to be modified *********************************//

    /*
     * request header
     * 1. HEADER_APP_KEY
     * 2. HEADER_APP_AUTH
     */
    public static final String HEADER_APP_KEY = "app_key";
    public static final String HEADER_APP_AUTH = "Authorization";
    
    /*
     * Application Access Security:
     * 1. APP_AUTH
     * 2. REFRESH_TOKEN
     */
    public static final String APP_AUTH = BASE_URL + "/iocm/app/sec/v1.1.0/login";
    public static final String REFRESH_TOKEN = BASE_URL + "/iocm/app/sec/v1.1.0/refreshToken";
    

    /*
     * Device Management:
     * 1. REGISTER_DEVICE
     * 2. MODIFY_DEVICE_INFO
     * 3. QUERY_DEVICE_ACTIVATION_STATUS
     * 4. DELETE_DEVICE
     * 5. DISCOVER_INDIRECT_DEVICE
     * 6. REMOVE_INDIRECT_DEVICE
     */
    public static final String REGISTER_DEVICE = BASE_URL + "/iocm/app/reg/v1.1.0/devices";
    public static final String MODIFY_DEVICE_INFO = BASE_URL + "/iocm/app/dm/v1.1.0/devices";
    public static final String QUERY_DEVICE_ACTIVATION_STATUS = BASE_URL + "/iocm/app/reg/v1.1.0/devices";
    public static final String DELETE_DEVICE = BASE_URL + "/iocm/app/dm/v1.1.0/devices";
    public static final String DISCOVER_INDIRECT_DEVICE = BASE_URL + "/iocm/app/signaltrans/v1.1.0/devices/%s/services/%s/sendCommand";
    public static final String REMOVE_INDIRECT_DEVICE = BASE_URL + "/iocm/app/signaltrans/v1.1.0/devices/%s/services/%s/sendCommand";

    /*
     * Data Collection:
     * 1. QUERY_DEVICES
     * 2. QUERY_DEVICE_DATA
     * 3. QUERY_DEVICE_HISTORY_DATA
     * 4. QUERY_DEVICE_CAPABILITIES
     * 5. SUBSCRIBE_NOTIFYCATION
     */
    public static final String QUERY_DEVICES = BASE_URL + "/iocm/app/dm/v1.3.0/devices";
    public static final String QUERY_DEVICE_DATA = BASE_URL + "/iocm/app/dm/v1.3.0/devices";
    public static final String QUERY_DEVICE_HISTORY_DATA = BASE_URL + "/iocm/app/data/v1.1.0/deviceDataHistory";
    public static final String QUERY_DEVICE_CAPABILITIES = BASE_URL + "/iocm/app/data/v1.1.0/deviceCapabilities";
    public static final String SUBSCRIBE_NOTIFYCATION = BASE_URL + "/iocm/app/sub/v1.1.0/subscribe";
    
    
    /*
     * Signaling Delivery锛�
     * 1. POST_ASYN_CMD
     * 2. QUERY_DEVICE_CMD
     * 3. UPDATE_ASYN_COMMAND
     * 4. CREATE_DEVICECMD_CANCEL_TASK
     * 5. QUERY_DEVICECMD_CANCEL_TASK
     *
     */
    public static final String POST_ASYN_CMD = BASE_URL + "/iocm/app/cmd/v1.4.0/deviceCommands";
    public static final String QUERY_DEVICE_CMD = BASE_URL + "/iocm/app/cmd/v1.4.0/deviceCommands";
    public static final String UPDATE_ASYN_COMMAND = BASE_URL + "/iocm/app/cmd/v1.4.0/deviceCommands/%s";
    public static final String CREATE_DEVICECMD_CANCEL_TASK = BASE_URL + "/iocm/app/cmd/v1.4.0/deviceCommandCancelTasks";
    public static final String QUERY_DEVICECMD_CANCEL_TASK = BASE_URL + "/iocm/app/cmd/v1.4.0/deviceCommandCancelTasks";


    /*
     * notify Type
     * serviceInfoChanged|deviceInfoChanged|LocationChanged|deviceDataChanged|deviceDatasChanged
     * deviceAdded|deviceDeleted|messageConfirm|commandRsp|deviceEvent|ruleEvent
     */
    public static final String DEVICE_ADDED = "deviceAdded";
    public static final String DEVICE_INFO_CHANGED = "deviceInfoChanged";
    public static final String DEVICE_DATA_CHANGED = "deviceDataChanged";
    public static final String DEVICE_DELETED = "deviceDeleted";
    public static final String MESSAGE_CONFIRM = "messageConfirm";
    public static final String SERVICE_INFO_CHANGED = "serviceInfoChanged";
    public static final String COMMAND_RSP = "commandRsp";
    public static final String DEVICE_EVENT = "deviceEvent";
    public static final String RULE_EVENT = "ruleEvent";
    public static final String DEVICE_DATAS_CHANGED = "deviceDatasChanged";

}

 

你可能感兴趣的:(Android从OceanConnect上获取数据)