본문 바로가기
공부/Spring

OpenAPI 데이터 받아오기

by son_i 2023. 9. 29.
728x90

weather 프로젝트에서 openweathermap API에 날씨 데이터를 받아오는 기능을 구현하였다.

 

1. API를 호출할 수 있는 String 작성. 

String apiUrl = "https://api.openweathermap.org/data/2.5/weather?q=seoul&appid=" + apiKey;

* apiKey는 보안상에 중요한 정보이므로 직접 기재하는 것이 아닌 application.properties에 'openweathermap.key=실제키 값'으로 작성해놓고 이 메소드 만든 클래스의 상단에 아래와 같이 작성.

@Value("${openweathermap.key}")
private String apiKey;

-> 장점 : 환경에 따라 유연한 값 설정 가능. 

 

2. URL 객체 생성

URL url = new URL(apiUrl);

*URL형식이 잘못된 경우 MalformedURLException을 throw. 이 예외는 IOException의 하위클래스임.

 

 

3. URL에서 URLConnection 객체 획득

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

*네트워크 연결은 connect() 메서드가 호출 될 때 명시적으로 이루어지거나,

헤더 필드를 읽거나 입/출력 스트림을 가져올 때 암시적으로 이루어짐.

 

 

4. URL 연결 구성

connection.setRequestMethod("GET");

 

5. 헤더필드 읽기

int responseCode = connection.getResponseCode();

*connect()로 명시해주지 않았지만 헤더필드를 읽음으로써 암시적으로 네트워크 연결이 실행된 거임 !!!

 

6. 입력 스트림 가져오기 및 데이터 읽기

BufferedReader br;
if (responseCode == 200) {
	br = new BufferedReader(new InputStreamReader(connection.getInputStream());
} else {
	br = new BufferedReader(new InputStreamReader(connection.getErrorStream());
}

*데이터를 문자열로 읽기위해 BufferedReader 사용. 전달 받은 데이터를 BufferedReader 객체로 저장.

 

7. 출력 스트림 가져오기 및 데이터 쓰기

String inputLine;
StringBuilder response = new StringBuilder();
while((inputLine = br.readLine()) != null) {
	response.append(inputLine);
}

*저장된 데이터를 라인별로 읽어 StringBuilder 객체로 저장.

 

7. 객체 해제

br.close();
conn.disconnect();