공공 데이터 가져오기
2024. 8. 19. 13:59ㆍJSP+Spring Boot
https://www.data.go.kr/index.do
여기서 한국환경공단_에어코리아_대기오염정보 에 담긴 데이터들을 가져오기
먼저 application.properties에 API 설정을 추가
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/KH_WORKBOOK
spring.datasource.username=root
spring.datasource.password=kh1234
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mappers/*.xml
#API 설정
#api.base-url=http://apis.data.go.kr/B552584/ArpltnInforInqireSvc/ : 대기오염 서비스 조회 공통 api -> RequestMapping
api.base-url=http://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty
#일반 인증키(Decoding)
api.key=일반 인증키
api.content-type=application/json
그리고 APISController를 작성해 공공 데이터를 받아옴
package com.kh.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
//공공 데이터 api를 이용한 api url 주소값 한 번 더 확인
@RequestMapping("/B552584/ArpltnInforInqireSvc") //대기오염 서비스 공공데이터 공통 주소
@RestController
public class APISController {
//시도별 실시간 측정정보 조회
@GetMapping("/getCtprvnRltmMesureDnsty")
public String getRealTimeInfo() {
return "측정결과전달";
}
}
그리고 이 데이터들을 리액트와 연결할 APIController도 작성
package com.kh.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.kh.service.APIService;
import org.springframework.web.bind.annotation.GetMapping;
@RestController
@RequestMapping("/api")
public class APIController {
@Autowired
private APIService apiService;
@GetMapping("/air-pollution")
public String getAirData() throws Exception {
String airData = apiService.getAirData();
System.out.println("airData : " + airData);
return airData;
}
}
그리고 데이터를 가져올 Service 작성
package com.kh.service;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class APIService {
//application.properties에 있는 값 가져오기
@Value("${api.base-url}")
private String baseUrl;
@Value("${api.key}")
private String apiKey;
@Value("${api.content-type}")
private String contentType;
public String getAirData() throws Exception {
//주소값 설정
String url = baseUrl;
url += "?serviceKey=" + URLEncoder.encode(apiKey, "UTF-8");
url += "&sidoName=" + URLEncoder.encode("서울", "UTF-8");
url += "&returnType-xml"; //서비스키와 서울지역 데이터키를 가져올 때 xml 파일로 가져옴
//세팅된 주소를 가지고 데이터 가져오기(헤더)
URL requestUrl = new URL(url);
//HttpURLConnection : 자바에서 특정 주소에 연결과 동시에 HttpMethod(get, post, put, delete) 요청을 보낼 수 있음
HttpURLConnection uc = (HttpURLConnection) requestUrl.openConnection();
uc.setRequestMethod("GET");
uc.setRequestProperty("Content-Type", contentType);
System.out.println("uc : " + uc);
//바디 - 남의 주소에서 남이 지정한 형식을 가져와야하기 떄문에 한 줄씩 읽어서 모두 실시간 가져오기
BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
StringBuilder response = new StringBuilder();
System.out.println("response 1 : " + response);
String line;
//데이터를 한 줄씩 가져오기
while((line = br.readLine()) != null) {
response.append(line);
}
br.close(); //데이터 다 가져오면 닫기
uc.disconnect();
//가져온 데이터 글자값으로 보여주기 위해 전달
return response.toString();
}
}
이제 리액트 파트
import React, {useState, useEffect} from 'react';
import axios from 'axios';
import './AirPollutionData.css';
const AirPollution = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
// API 호출
axios.get('http://localhost:8081/api/air-pollution')
.then((response) => {
const parser = new DOMParser();
//공공데이터는 xml 형식이므로 xml으로 형식으로 변경
const xml = parser.parseFromString(response.data, "text/xml");
const items = xml.getElementsByTagName("item");
const parsedData = Array.from(items).map(item => {
const fullDateTime = item.getElementsByTagName("dataTime")[0]?.textContent;
const yearMonth = fullDateTime ? fullDateTime.slice(0, 7) : 'N/A';
return {
dataTime : yearMonth,
stationName: item.getElementsByTagName("stationName")[0]?.textContent,
so2Grade: item.getElementsByTagName("so2Grade")[0]?.textContent,
coFlag: item.getElementsByTagName("coFlag")[0]?.textContent,
khaiValue: item.getElementsByTagName("khaiValue")[0]?.textContent,
pm10Value: item.getElementsByTagName("pm10Value")[0]?.textContent,
no2Value: item.getElementsByTagName("no2Value")[0]?.textContent,
o3Value: item.getElementsByTagName("o3Value")[0]?.textContent
};
});
setData(parsedData);
setLoading(false);
})
.catch((error) => {
setError(error);
setLoading(false);
});
}, []);
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return(
<div>
<h1 className='heading'>공공 공기 데이터 조회</h1>
<div className='card-container'>
{/* data들을 가져와 item으로 하나씩 꺼내서 데이터 보기 */}
{data.map((item, index) => (
<div key={index} className='card'>
<h2 className='stationName'>{item.stationName}</h2>
<p><strong>년-월 : </strong>{item.dataTime}</p>
<p><strong>SO2 등급 : </strong>{item.so2Grade}</p>
<p><strong>CO 상태 : </strong>{item.coFlag}</p>
<p><strong>종합대기질 지수 : </strong>{item.khaiValue}</p>
<p><strong>PM10 농도 : </strong>{item.pm10Value}</p>
<p><strong>NO0 농도 : </strong>{item.no2Value}</p>
<p><strong>O3 농도 : </strong>{item.o3Value}</p>
</div >
))}
</div>
</div>
)
}
export default AirPollution;
시현 화면
'JSP+Spring Boot' 카테고리의 다른 글
JPA + Modal 맛보기 (0) | 2024.08.20 |
---|---|
중복 확인하기(ajax) (0) | 2024.07.09 |
이메일 인증 (0) | 2024.06.26 |
마이페이지 조회,수정, 삭제, 검색 (0) | 2024.06.25 |
로그인 (0) | 2024.06.25 |