Spring Boot) open api 활용하여 데이터 받기

박우영·2023년 4월 6일
0

자바/코틀린/스프링

목록 보기
19/35

먼저 이 게시글은 프로젝트 진행하며 open api 활용해야 하는 부분이 끝날때까지 작성하고 수정 할 예정입니다.

solved ac api 비공식 문서를 사용하였습니다.

https://solvedac.github.io/unofficial-documentation/#/operations/verifyAccountCredentials
위 사이트를 참조 하였습니다.

요구사항으로는

  • 문제풀이 개수
  • 난이도 별 문제수

위 두가지를 teamrule 과 비교하여 미션 성공 실패 유무를 체크하고
미션을 실패할경우 line notify 를 통해 실패 메시지 전달하는 것 입니다.

데이터는 아래 사진과 같이 json 형태로 나옵니다.

2023.04.06 - 게시글 첫 작성(계획 수립/api 호출 성공)


SolvedApiManager class

    private final String BASE_URL = "https://solved.ac/api/v3/user";
    private final String api_user = "/show";
    private final String api_problem = "/problem_stats";
    private final String api_handle = "?handle=";

    private User user;

    private String getUserInformation() throws UnsupportedEncodingException {
        return BASE_URL +
                api_user +
                api_handle + "wy9295";
    }

    private String getProblemStats() throws UnsupportedEncodingException{
        RestTemplate restTemplate = new RestTemplate();
        return BASE_URL +
                api_problem +
                api_handle + "wy9295";
    }


    //==문제풀이 로직==//
    public Integer getSolvedCount() throws IOException, ParseException {
        RestTemplate restTemplate = new RestTemplate();
        String jsonString = restTemplate.getForObject(getUserInformation(), String.class);

        JSONParser jsonParser = new JSONParser();
        Object jsonObject = jsonParser.parse(jsonString);

        JSONObject jsonBody = (JSONObject) jsonObject;

        return (Integer) jsonBody.get("solvedCount");
    }

    public JSONArray getProblemCount() throws IOException, ParseException {
        RestTemplate restTemplate = new RestTemplate();
        String jsonString = restTemplate.getForObject(getProblemStats(), String.class);

        JSONParser jsonParser = new JSONParser();
        Object jsonObject = jsonParser.parse(jsonString);

        JSONArray jsonArray = (JSONArray) jsonObject;

        return jsonArray;
    }

요구사항인 문제풀이 개수와, 문제 level 별 문제 풀이 개수 파싱 작업

controller 에 선택한 레벨에 맞는 문제풀이 수 출력 로직 작성(임시)

    @Autowired
    private UserService userService;

    @Autowired
    private SolvedApiManager solvedApiManager;
    

    @GetMapping("/test")
    public JSONArray fetch2() throws IOException, ParseException, UnsupportedEncodingException{
        JSONArray test = this.solvedApiManager.getProblemCount();
        if (test.size() > 0) {
            for (int i = 0; i < test.size(); i++) {
                JSONObject jsonObj = (JSONObject) test.get(i);
                if (jsonObj.get("level").equals(1L)) {
                    System.out.println(jsonObj.get("solved"));
                }
            }
        }
        return test;
    }

성공, 실패유무 체크

public enum SolvedStatus {
    COMPLETE, FAIL
}

TeamRule 에 따른 미션 수행유무 확인을 위해 SolvedStatus 생성

현 상황에서 추가 작업 필요하다고 느끼는 것

  • null 값 체크, 예외처리 추가 필요
  • repository에 값 저장 후 날짜별 비교 로직

2023.04.09 - json 파싱


0개의 댓글