2024. 6. 24. 22:38ㆍSpring-Project
JAVA :17
개발 OS : Window
IDE : IntelliJ
기상청 API를 활용하여 날씨 정보를 실시간으로 확인하고 일주일 예상 날씨를 구할 것이다.
먼저 기상청 단기예보 API 키를 발급받아야 한다.
아래 사이트에 회원가입을 하고 활용신청을 클릭하면 바로 발급된다.
https://www.data.go.kr/data/15084084/openapi.do
기상청_단기예보 ((구)_동네예보) 조회서비스
초단기실황, 초단기예보, 단기((구)동네)예보, 예보버전 정보를 조회하는 서비스입니다. 초단기실황정보는 예보 구역에 대한 대표 AWS 관측값을, 초단기예보는 예보시점부터 6시간까지의 예보를,
www.data.go.kr
우리가 필요한 것은 일반인증키이다. 인코딩 디코딩 둘 중 잘 되는 것으로 선택하면 된다.
위 키값을 복사해서 잘 보관해 둔다.
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.io.BufferedReader;
import java.io.IOException;
public class ApiExplorer {
public static void main(String[] args) throws IOException {
StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst"); /*URL*/
urlBuilder.append("?" + URLEncoder.encode("serviceKey","UTF-8") + "=서비스키"); /*Service Key*/
urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8") + "=" + URLEncoder.encode("1", "UTF-8")); /*페이지번호*/
urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8") + "=" + URLEncoder.encode("1000", "UTF-8")); /*한 페이지 결과 수*/
urlBuilder.append("&" + URLEncoder.encode("dataType","UTF-8") + "=" + URLEncoder.encode("XML", "UTF-8")); /*요청자료형식(XML/JSON) Default: XML*/
urlBuilder.append("&" + URLEncoder.encode("base_date","UTF-8") + "=" + URLEncoder.encode("20210628", "UTF-8")); /*‘21년 6월 28일발표*/
urlBuilder.append("&" + URLEncoder.encode("base_time","UTF-8") + "=" + URLEncoder.encode("0500", "UTF-8")); /*05시 발표*/
urlBuilder.append("&" + URLEncoder.encode("nx","UTF-8") + "=" + URLEncoder.encode("55", "UTF-8")); /*예보지점의 X 좌표값*/
urlBuilder.append("&" + URLEncoder.encode("ny","UTF-8") + "=" + URLEncoder.encode("127", "UTF-8")); /*예보지점의 Y 좌표값*/
URL url = new URL(urlBuilder.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-type", "application/json");
System.out.println("Response code: " + conn.getResponseCode());
BufferedReader rd;
if(conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
System.out.println(sb.toString());
}
}
위 API에서 제공해 주는 샘플 예제 코드이다.
StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst"); /*URL*/
첫 번째는 내가 가져올 데이터 API 링크이다.
위 링크는 초단기실황조회이다.
http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst
위 링크는 초단기예보조회이다.
http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst
위 링크는 단기예보조회이다.
http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getFcstVersion
위 링크는 예보버전조회이다.
우리가 필요한 것은 단기예보 조회 이므로 코드의 URL를 단기예보조회로 바꿔주자.
StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst");
다음으로는 서비스 키다.
urlBuilder.append("?" + URLEncoder.encode("serviceKey","UTF-8") + "="+ 내 서비스키);
ex)
만약 서비스 키가 "ABCDEFG" 일 때
urlBuilder.append("?" + URLEncoder.encode("serviceKey","UTF-8") + "="+ "ABCDEFG");
or
String key = "ABCDEFG"
urlBuilder.append("?" + URLEncoder.encode("serviceKey","UTF-8") + "="+ key);
앞서 발급받았던 인증키를 넣어주면 된다.
인코딩 or 디코딩 키를 넣어주면 된다.
다음으로는 페이지 번호, 페이지 결과 수이다. 그냥 놔두면 된다.
만약 내가 조금 받고 싶다면 페이지 결과 수를 줄이면 된다.
urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8") + "=" + URLEncoder.encode("1", "UTF-8")); /*페이지번호*/
urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8") + "=" + URLEncoder.encode("1000", "UTF-8")); /*한 페이지 결과 수*/
다음으로는 요청 자료를 어떤 형식으로 받을 것인지 결정하면 된다.
나는 JSON으로 받을 것이다.
urlBuilder.append("&" + URLEncoder.encode("dataType","UTF-8") + "=" + URLEncoder.encode("JSON", "UTF-8")); /*요청자료형식(XML/JSON) Default: XML*/
다음으로는 요청 날짜와 시간이다.
현재 날짜 기준으로 -48시간 ~ 96시간 (2일 전 ~ 4일 후)까지 데이터를 볼 수 있다.
그리고 단기예보 시간은 1일 8회를 제공해 주며 0200, 0500, 0800, 1100, 1400, 1700, 2000, 2300 이렇게 있다.
API에 데이터 업데이트 시간은 위 시간의 + 10분을 해줘야 하며 0200시 데이터를 출력하고 싶으면
02시 10분 이후에 검색하면 된다.
ex) 02시의 데이터를 알고 싶다 -> 0210
// 현재 날짜가 24년 6월 24일, 시간은 22시일 때
20240624 , 2000를 검색해야 한다.
위 적혀있는 8개 숫자를 제외한 숫자 검색 시 오류가 뜬다.
urlBuilder.append("&" + URLEncoder.encode("base_date","UTF-8") + "=" + URLEncoder.encode("20240624", "UTF-8")); /*‘21년 6월 28일발표*/
urlBuilder.append("&" + URLEncoder.encode("base_time","UTF-8") + "=" + URLEncoder.encode("2000", "UTF-8")); /*05시 발표*/
마지막으로 현재 위치의 좌표값을 넣어야 한다.
기상청 API를 발급받았던 곳에 파일이 있다.
엑셀 파일에 자신이 살고 있는 지역을 찾아 x, y에 넣으면 된다.
내가 있는 지역의 경우 x=64, y = 123으로 나온다.
urlBuilder.append("&" + URLEncoder.encode("nx","UTF-8") + "=" + URLEncoder.encode("64", "UTF-8")); /*예보지점의 X 좌표값*/
urlBuilder.append("&" + URLEncoder.encode("ny","UTF-8") + "=" + URLEncoder.encode("123", "UTF-8")); /*예보지점의 Y 좌표값*/
이제 데이터를 요청할 준비가 끝났다.
이제 코드를 실행하면 JSON 데이터가 나온다
Response code: 200
{"response":{"header":{"resultCode":"00","resultMsg":"NORMAL_SERVICE"},
"body":{"dataType":"JSON","items":{"item":[{"baseDate":"20240624","baseTime":"2000","category":"TMP","fcstDate":"20240624",
"fcstTime":"2100","fcstValue":"22","nx":55,"ny":127},
{"baseDate":"20240624","baseTime":"2000","category":"UUU","fcstDate":"20240624","fcstTime":"2100","fcstValue":"2.1","nx":55,"ny":127},{"baseDate":"20240624","baseTime":"2000","category":"VVV","fcstDate":"20240624","fcstTime":"2100","fcstValue":"-0.9","nx":55,"ny":127},
{"baseDate":"20240624","baseTime":"2000","category":"VEC", ...중략
위처럼 Response code가 200 나오고 아래 JSON 데이터가 나오면 정상적으로 출력된 것이다.
'Spring-Project' 카테고리의 다른 글
기상청API를 활용한 나만의 Weather 만들기(3) - domain, repository, service (0) | 2024.07.02 |
---|---|
기상청API를 활용한 나만의 Weather 만들기(2) - 기상청API 데이터 분석 (0) | 2024.06.25 |
Arduino와 SpringBoot를 사용한 온습도 측정 사이트(완) - SpringBoot편 (0) | 2024.06.19 |
Arduino와 SpringBoot를 사용한 온습도 측정 사이트(7) - SpringBoot편 (0) | 2024.06.18 |
Arduino와 SpringBoot를 사용한 온습도 측정 사이트(6) - SpringBoot편 (0) | 2024.06.17 |