巢更改target_tempreture_f:如何使用Java HTTP放置在Android代码中嵌套恒温器的目标温度?
-
02-01-2020 - |
题
nest change target_temperature_f:如何使用Java HTTP放置Android代码的巢恒温器的目标温度?
解决方案
您可以使用httpclient或httpurlconnection来调用来自Android的REST API上的Put。以下是一个使用httpurlconnection的示例。
注意:建议您缓存每个用户/访问令牌的重定向URL,并为该用户的所有后续呼叫重复使用它。
- 假设在此,基本以 https://developer-api.nest.com/
-
如果urlconnection的返回代码是307(重定向),则会缓存位置并使用该位置以发出所提出请求。(注意此处的缓存表示某种的全局缓存/同时映射帧)
.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;
}
不隶属于 StackOverflow