Nest change target_tempreture_f:如何在android代码中使用java http PUT设置Nest Thermostat的目标温度?

时间:2014-08-01 17:53:42

标签: android-networking nest-api

Nest change target_temperature_f:如何使用java http PUT通过android代码设置Nest Thermostat的目标温度?

1 个答案:

答案 0 :(得分:3)

您可以使用HttpClient或HttpURLConnection从Android调用其余API上的PUT。以下是使用HttpURLConnection的示例。

注意:建议您缓存每个用户/访问令牌的重定向URL,并将其重新用于该用户的所有后续调用。

  1. 这里假设开头的基础是https://developer-api.nest.com/
  2. 如果来自urlconnection的返回码是307(重定向),则缓存该位置并将其用于发出放置请求。 (注意这里的缓存表示某种全局缓存/ concurrentMap)

    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;
    

    }