Search code examples
android-networkingnest-api

Nest change target_tempreture_f : How to use java http PUT to set target temperature of the Nest Thermostat in android code?


Nest change target_temperature_f : How to use java http PUT to set the target temperature of the Nest Thermostat by android code?


Solution

  • You can use either HttpClient or HttpURLConnection for calling a PUT on the rest API from Android. Here is an example using HttpURLConnection.

    Note: It is advised that you cache the Redirect URL per user/access token and reuse it for all subsequent calls for that user.

    1. Assume here that the base to start with is https://developer-api.nest.com/
    2. If the return code from the urlconnection is a 307 (redirect), then cache the location and use that for issuing a put request. (Note the cache here indicates a global cache/ concurrentMap of some kind)

      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;
      

      }