728x90
반응형
학습내용
1. 공공데이터 회원 가입 후 발급 신청
2. postman 회원가입 및 API 발급 테스트
3. 소스 적용 방법
공공데이터 회원 가입 후 발급 신청
1. 공공데이터포털 로그인 후 발급 신청
postman 회원가입 및 API 발급 테스트
postman을 사용 하는 이유는 해당 API가 제대로 신청이 됐는지 파악 하기 위해 사용 하는 툴입니다.
1. postman 회원가입 https://www.postman.com/
2. 좌측에 컬렉션스 클릭 후 프로젝트 생성하기
3. 이제 다시 승인 받은 공공데이터 상세 화면으로 이동
4. End Point 뒤에다 원하는 국문을 추가
6. postman 테스트(저자 공휴일 정보조회 테스트)
Send 부분 추가
http://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/getRestDeInfo |
나머지 키값 원하는 연도 넣기 마지막 서비스키는 일반 인증키(Encoding) 본인거 넣어주면 끝
결과 값
소스 적용 방법
1. 공공데이터 다시 들어가서 상세보기에서 맨 밑으로 가면 샘플코드 있음 (저자는 Java 활용)
2. 원하는 언어로 코드 작성 해서 API호출 하면 됨
작업 오더 :
사용자가 작업을 요청 할때 회답기한일의 날짜(14일 기준)가 주말이거나 공휴일 일때는 +1일 해달라는 요청
코드 설명 :
1. 현재 날짜 기준으로 캘린더에 14일 후 날짜 저장2. 저장된 날을 기준으로 주말 함수 사용으로 요일 확인3. 해당 요일이 6(토요일), 7(일요일) 이면 캘린더에 +1 일을 한 다음 while 문으로 반복 4. 요일이 주말이 아니라면 빠져나와 공휴일 검사 공휴일 걸리면 +1 만약 안걸리면 해당 요일 오브젝트 저장
public void Workingday(Map<String, Object> paramMap, ModelMap model) throws IOException {
System.out.println("Workingday impl call() ");
try {
boolean outerCondition = true;
//*********************************************** 오늘 날짜 구하기
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd"); // 현재 날짜 변환문
cal.add(Calendar.DATE, 14); // 날짜 설정 14일 후 (비용추계)
String requstLastDay = sdf1.format(cal.getTime()); // 14일 후 날짜 값 저장
System.out.println("requstLastDay :"+ requstLastDay);
int year = Integer.parseInt(requstLastDay.substring(0, 4));
int month = Integer.parseInt(requstLastDay.substring(4, 6));
int day = Integer.parseInt(requstLastDay.substring(6, 8));
while (outerCondition) {
//*********************************************** 주말구하기
LocalDate weekend = LocalDate.of(year, month, day); // 요일 확인
DayOfWeek dayOfWeek = weekend.getDayOfWeek(); // 주말 확인
int numday = dayOfWeek.getValue();
System.out.println("what weekedn: " + numday);
if(numday == 6 || numday == 7) {
cal.add(Calendar.DATE, 1);
System.out.println("주말 확인 완료 1일 추가 : "+ sdf1.format(cal.getTime()));
year = Integer.parseInt(sdf1.format(cal.getTime()).substring(0, 4));
month = Integer.parseInt(sdf1.format(cal.getTime()).substring(4, 6));
day = Integer.parseInt(sdf1.format(cal.getTime()).substring(6, 8));
requstLastDay = sdf1.format(cal.getTime());
continue;
}else {
//*********************************************** 공휴일 구하기
StringBuilder urlBuilder = new StringBuilder("http://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService/getRestDeInfo");
urlBuilder.append("?" + URLEncoder.encode("solYear", "UTF-8") + "=" + URLEncoder.encode(Integer.toString(year), "UTF-8"));
urlBuilder.append("&" + URLEncoder.encode("solMonth", "UTF-8") + "=" + URLEncoder.encode(String.format("%02d", month), "UTF-8"));
urlBuilder.append("&" + URLEncoder.encode("serviceKey", "UTF-8") + "=본인 일반 인증키 값 넣기");
System.out.println("urlBuilder :" + urlBuilder);
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("xml확인 :"+sb.toString());
// XML 파싱
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
ByteArrayInputStream input = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
Document document = builder.parse(input);
// XPath 초기화
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
XPathExpression expr = xPath.compile("/response/body/items/item/locdate/text()");
String locdate = (String) expr.evaluate(document, XPathConstants.STRING);
System.out.println("공휴일 날짜 : " + locdate);
if (!locdate.isEmpty()) {
requstLastDay =sdf1.format(cal.getTime()); ;
if(requstLastDay.equals(locdate)) {
cal.add(Calendar.DATE, 1);
requstLastDay =sdf1.format(cal.getTime());
year = Integer.parseInt(sdf1.format(cal.getTime()).substring(0, 4));
month = Integer.parseInt(sdf1.format(cal.getTime()).substring(4, 6));
day = Integer.parseInt(sdf1.format(cal.getTime()).substring(6, 8));
System.out.println("공휴일 확인 1일 추가 : "+ sdf1.format(cal.getTime()));
continue;
}
}else {
System.out.println("해당월은 공휴일이 없습니다.");
}
}
outerCondition = false;
String workLimitDt = sdf1.format(cal.getTime());
System.out.println("날짜 확인: :"+ workLimitDt);
model.addAttribute("workLimitDt", workLimitDt);
}
} catch (Exception e) {
e.printStackTrace();
}
}
728x90
반응형
'오류 해결 및 새로운 지식 > API활용 및 오류 해결' 카테고리의 다른 글
개발자 화나는 literal does not match format string 오류 해결법 (0) | 2023.10.18 |
---|---|
(JAVA) 클라이언트(접속자) IP주소 설정 개발(IPv6 > IPv4 변환) (0) | 2023.08.25 |