作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
Nest change target_temperature_f : 如何使用 java http PUT 通过 android 代码设置 Nest Thermostat 的目标温度?
最佳答案
您可以使用 HttpClient 或 HttpURLConnection 在 Android 的其余 API 上调用 PUT。这是一个使用 HttpURLConnection 的示例。
注意:建议您缓存每个用户/访问 token 的重定向 URL,并将其重新用于该用户的所有后续调用。
如果 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;
关于android-networking - 嵌套更改 target_tempreture_f : How to use java http PUT to set target temperature of the Nest Thermostat in android code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25085956/
Nest change target_temperature_f : 如何使用 java http PUT 通过 android 代码设置 Nest Thermostat 的目标温度? 最佳答案 您可
我是一名优秀的程序员,十分优秀!