둥지 변경 target_tempreture_f : Java HTTP를 사용하는 방법 안드로이드 코드에서 둥지 온도 조절기의 목표 온도를 설정하려면?
-
02-01-2020 - |
문제
둥지 변경 target_temperature_f : Java HTTP를 사용하는 방법 안드로이드 코드로 둥지 온도 조절기의 목표 온도를 설정하려면?
해결책
안드로이드에서 REST API를 호출하기 위해 HTTPClient 또는 HttpUrlConnection을 사용할 수 있습니다.httpurlconnection을 사용하는 예제는 다음과 같습니다.
참고 : 사용자 / 액세스 토큰 당 리디렉션 URL을 캐시하고 해당 사용자에 대한 모든 후속 호출에 대해 재사용하는 것이 좋습니다.
- 여기에 기초가 시작되는 것은 "nofollow"> https://developer-api.nest.com/
-
URLConnection의 리턴 코드가 307 (리디렉션)이면 위치를 캐시하고 Put 요청을 발행하는 데 사용할 수 있습니다.(여기서는 캐시를 나타내는 캐시는 일부 종류의 전역 캐시 / 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;
}
제휴하지 않습니다 StackOverflow