[개발] 프로그램 지식

[api] api 주소를 활용해서 json 데이터 받는 방법

  • -
반응형

1. controller에서 작성

2. url 연결

3. get or post 방식 결정

4. 타입 결정

5. 출력가능한 상태인지 확인

6. 결과값 받기

7. 정상적으로 받은 경우  JSON을 리스트 형식으로 받아서 반환

	@RequestMapping(value = "/00.do")
	public ResponseEntity<?> 00(@RequestParam Map<String, Object> commandMap, HttpServletRequest request, ModelMap model) throws Exception {

		LOGGER.debug(commandMap.toString());
		
		Map<String, Object> resultMap = new HashMap<>();

        try {
            URL url = new URL("https:/000000000000000000000000000");

            // URL 연결
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // GET 방식인지, POST 방식인지
            conn.setRequestMethod("POST");

            // 받는 API에 따라 맞는 Content-Type을 정해주면 됩니다.
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 서버에서 온 데이터를 출력할 수 있는 상태인지
            conn.setDoOutput(true);

            // 보내고 결과값 받기
            int responseCode = conn.getResponseCode();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            StringBuilder response = new StringBuilder();
            String inputLine;

            while ((inputLine = in.readLine()) != null) { // Response 출력
                response.append(inputLine);
            }

            if (responseCode == 200 || responseCode == 201) {
                String jsonStr = response.toString();
                JSONParser parser = new JSONParser();

                // JSON 배열로 파싱
                List<Map<String, Object>> resultMap2 = (List<Map<String, Object>>) parser.parse(jsonStr);

                // JSON 배열을 List<Map<String, Object>>로 변환
                /*List<Map<String, Object>> dataArray = new ArrayList<>();
                for (Object obj : jsonArray) {
                    if (obj instanceof Map) {
                        dataArray.add((Map<String, Object>) obj);
                    }
                }*/

                // ResponseEntity로 성공 응답 반환
                return new ResponseEntity<>(resultMap2, HttpStatus.OK);
            } else {
                // ResponseEntity로 오류 응답 반환
                resultMap.put("msg", "Error"); // 에러 메시지
                resultMap.put("code", responseCode); // HTTP 응답 코드
                resultMap.put("time", System.currentTimeMillis()); // 현재 시간
                return new ResponseEntity<>(resultMap, HttpStatus.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            // ResponseEntity로 예외 응답 반환
            resultMap.put("msg", "Exception"); // 예외 메시지
            resultMap.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value()); // HTTP 응답 코드
            resultMap.put("time", System.currentTimeMillis()); // 현재 시간
            return new ResponseEntity<>(resultMap, HttpStatus.INTERNAL_SERVER_ERROR);
        }
		
		
	}

 

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.