Nest change target_temperature_f : 如何使用 java http PUT 通过 android 代码设置 Nest Thermostat 的目标温度?
问问题
414 次
1 回答
3
您可以使用 HttpClient 或 HttpURLConnection 从 Android 调用其余 API 上的 PUT。这是一个使用 HttpURLConnection 的示例。
注意:建议您缓存每个用户/访问令牌的重定向 URL,并将其用于该用户的所有后续调用。
- 假设这里开始的基础是https://developer-api.nest.com/
如果 urlconnection 的返回码是 307(重定向),则缓存该位置并将其用于发出 put 请求。(注意这里的缓存表示某种全局缓存/并发映射)
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;
}
于 2014-08-04T19:59:04.997 回答