스케줄을 생성하는 토이 프로젝트를 진행하다가 사용 기간을 정하고 싶어졌다.
처음엔 val expiration = "2021-05-01"
(사용기한)과 val today = LocalDate.now()
를 비교하여 today
가 expiration
보다 크면 프로그램을 종료했다.
하지만 사용자가 윈도우 시간을 변경하여 LocalDate.now()
를 조작할 수 있기 때문에
World Time Api를 호출하여 서버 시간을 가져오는 방식으로 변경했다.
사용한 api url은 worldtimeapi.org/api/timezone/Asia/Seoul
이고
요청했을 때 결과는 다음과 같다.
Api에 요청한 과정은 다음과 같다.
1. 요청을 날릴 URL을 초기화한다.
2. URL로부터 connection을 생성한다.
3. 요청에 필요한 설정(method type 등)을 지정한다.
4. 응답을 받아온다.
이를 코드로 나타내면 다음과 같다.
object RequestIO {
private val url = URL("http://worldtimeapi.org/api/timezone/Asia/Seoul")
private val connection = url.openConnection() as HttpURLConnection
private fun sendRequest(): String {
connection.requestMethod = "GET"
val responseCode = connection.responseCode
if (responseCode != 200) {
println("인터넷 연결상태를 확인해주세요\n")
println("시스템을 종료합니다.\n")
exitProcess(-1)
}
val reader = BufferedReader(InputStreamReader(connection.inputStream))
val httpResponse = StringBuffer()
while (true) {
val input = reader.readLine()
if (input.isNullOrEmpty())
break
else
httpResponse.append(input)
}
return httpResponse.toString()
}
}
api 서버가 정상적으로 작동한다면
요청을 했을 때 Response를 json 형식으로 받아올 수 있다.
Response: {"abbreviation":"KST","client_ip":"106.244.74.67","datetime":"2021-05-03T15:09:57.547654+09:00","day_of_week":1,"day_of_year":123,"dst":false,"dst_from":null,"dst_offset":0,"dst_until":null,"raw_offset":32400,"timezone":"Asia/Seoul","unixtime":1620022197,"utc_datetime":"2021-05-03T06:09:57.547654+00:00","utc_offset":"+09:00","week_number":18}