Nest Change Target_Tempreture_f: Come utilizzare Java HTTP Metti per impostare la temperatura target del termostato Nest nel codice Android?

StackOverflow https://stackoverflow.com//questions/25085956

  •  02-01-2020
  •  | 
  •  

Domanda

Nest Change Target_temperature_f: Come utilizzare Java HTTP Metti per impostare la temperatura target del termostato Nest per codice Android?

È stato utile?

Soluzione

È possibile utilizzare httpClient o httpurlConnection per chiamare un messaggio indossato sull'API del resto da Android.Ecco un esempio usando httpurlconnection.

Nota: si consiglia di cache sull'URL di reindirizzamento per utente / accessi al token e riutilizzarlo per tutte le chiamate successive per quell'utente.

    .
  1. Supponi qui che la base da iniziare è https://developer-api.nest.com/
  2. Se il codice di ritorno dall'URLConnection è un 307 (reindirizzamento), quindi cache la posizione e utilizzalo per il rilascio di una richiesta di messa.(Nota la cache qui indica una cache globale / concordrentmap di qualche tipo)

    public static int setThermostatTemperatureF(int temperatureF,
        String base, String thermostatId, String accessToken) throws IOException {
    try {
        String tChangeUrl = String.format("%s/devices/thermostats/%s/target_temperature_f?auth=%s",
                base, thermostatId, accessToken);
        URL url = new URL(tChangeUrl);
        HttpsURLConnection ucon = (HttpsURLConnection) url.openConnection();
        ucon.setRequestProperty("Content-Type", "application/json");
        ucon.setRequestMethod("PUT");
        ucon.setDoOutput(true);
        // Write the PUT body
        OutputStreamWriter writer = new OutputStreamWriter(ucon.getOutputStream());
        writer.append(Integer.toString(temperatureF));
        writer.flush();
    
        int responseCode = ucon.getResponseCode();
        if (responseCode == 307) { // temporary redirect
            // cache the URL for future uses for this User
            String redirectURL = ucon.getHeaderField("Location");
            URI u = new URI(redirectURL);
            StringBuilder baseUrl = new StringBuilder(u.getScheme())
                    .append("://").append(u.getHost());
            if (u.getPort() != 0) {
                baseUrl.append(":").append(u.getPort());
            }
            baseUrl.append("/");
            cache.put(accessToken, baseUrl.toString());
            return setThermostatTemperatureF(temperatureF, baseUrl.toString(), thermostatId, accessToken);
        } else {
            return responseCode;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return -1;
    
    .

    }

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top