카카오 공휴일 API - kakao gonghyuil API

# OpenAPI 키 발행: //www.data.go.kr/data/15012690/openapi.do 

# 서비스 키를 발급 받아야합니다.

# 프로젝트 구조

- ApiController.java

- RequestUtils.java 

 

1. 공공데이터에서 제공해주는 Java 버전의 API를 살짝 각색합니다.

  Year과 Month를 넣는 부분과 Json 형식으로 요청합니다.

2. Json으로 받은 데이터를 Hashmap으로 변환합니다.

반응형

# 1번과 2번 소스코드

private static String secretKey = "서비스키"; public static Map<String, Object> holidayInfoAPI(String year, String month) throws IOException { StringBuilder urlBuilder = new StringBuilder("//apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/getHoliDeInfo"); /*URL*/ urlBuilder.append("?" + URLEncoder.encode("serviceKey", "UTF-8") + "=" + secretKey); /*Service Key*/ urlBuilder.append("&" + URLEncoder.encode("pageNo", "UTF-8") + "=" + URLEncoder.encode("1", "UTF-8")); /*페이지번호*/ urlBuilder.append("&" + URLEncoder.encode("numOfRows", "UTF-8") + "=" + URLEncoder.encode("10", "UTF-8")); /*한 페이지 결과 수*/ urlBuilder.append("&" + URLEncoder.encode("solYear", "UTF-8") + "=" + URLEncoder.encode(year, "UTF-8")); /*연 */ urlBuilder.append("&" + URLEncoder.encode("solMonth", "UTF-8") + "=" + URLEncoder.encode(month.length() == 1 ? "0" + month : month, "UTF-8")); /*월*/ urlBuilder.append("&" + URLEncoder.encode("_type", "UTF-8") + "=" + URLEncoder.encode("json", "UTF-8")); /* json으로 요청 */ URL url = new URL(urlBuilder.toString()); System.out.println("요청URL = " + urlBuilder); 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()); return string2Map(sb.toString()); } /** * Json String을 Hashmap으로 반환 * * @param json * @return */ public static Map<String, Object> string2Map(String json) { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = null; try { map = mapper.readValue(json, Map.class); System.out.println(map); } catch (IOException e) { e.printStackTrace(); } return map; }

3. Controller 구성

* 공휴일 요청 후, 세 가지의 응답을 받게 됩니다.

  1. 공휴일이 없는 경우 

  2. 공휴일 하루 있는 경우

  3. 공휴일 이틀 이상인 경우

 

 

@GetMapping("holidayInfoAPI") public ResponseEntity holidayInfoAPI( @PathParam("year") String year, @PathParam("month") String month ) { System.out.println("year = " + year); System.out.println("month = " + month); ArrayList<HashMap> responseHolidayArr = new ArrayList<>(); try { Map<String, Object> holidayMap = RequestUtils.holidayInfoAPI(year, month); Map<String, Object> response = (Map<String, Object>) holidayMap.get("response"); Map<String, Object> body = (Map<String, Object>) response.get("body"); System.out.println("body = " + body); int totalCount = (int) body.get("totalCount"); if (totalCount <= 0) { System.out.println("공휴일 없음"); } if (totalCount == 1) { HashMap<String, Object> items = (HashMap<String, Object>) body.get("items"); HashMap<String, Object> item = (HashMap<String, Object>) items.get("item"); responseHolidayArr.add(item); System.out.println("item = " + item); } if (totalCount > 1) { HashMap<String, Object> items = (HashMap<String, Object>) body.get("items"); ArrayList<HashMap<String, Object>> item = (ArrayList<HashMap<String, Object>>) items.get("item"); for (HashMap<String, Object> itemMap : item) { System.out.println("itemMap = " + itemMap); responseHolidayArr.add(itemMap); } } } catch (IOException e) { e.printStackTrace(); } return ResponseEntity.ok().body(responseHolidayArr); }

4. 결과 화면

 

 

 

 

공유하기

게시글 관리

구독하기미나미 블로그

저작자표시 비영리 변경금지

  • 카카오스토리
  • 트위터
  • 페이스북

'[Spring] > springboot' 카테고리의 다른 글

[SpringBoot] 멀티 데이터베이스 설정하기 - Gradle 설정편  (0)2022.05.22[SpringBoot] 공공데이터포털 활용 과거 날씨 시간별 정보 받기  (0)2022.04.16[SpringBoot] RestAPI 파일업로드 - 2  (0)2022.02.24[SpringBoot] RestAPI 파일업로드 - 1  (0)2022.02.24[SpringBoot] 스프링 Autoconfiguration 이해하기  (0)2021.03.15

Toplist

최신 우편물

태그