투케이2K

88. (TWOK/ALGORITHM) [Spring] 문법 - RestTemplate 레스트 템플릿 사용해 get , post query param (쿼리 파람) 요청 본문

투케이2K 알고리즘

88. (TWOK/ALGORITHM) [Spring] 문법 - RestTemplate 레스트 템플릿 사용해 get , post query param (쿼리 파람) 요청

투케이2K 2023. 1. 22. 12:51
반응형

[환경 설정 및 설명]

언어 / 플랫폼 : Java / Spring

설 명 : 문법 - RestTemplate 레스트 템플릿 사용해 get , post query param (쿼리 파람) 요청

 

[소스 코드]

    // TODO [SEARCH FAST] : [레스트 템플릿 테스트]
    @GetMapping("/REST_TAMPLATE")
    public String REST_TAMPLATE(@RequestParam Map<String, String> param){
        System.out.println("\n");
        System.out.println("================================================");
        System.out.println("[CLASS] : "+String.valueOf(CLASS_NAME));
        System.out.println("[METHOD] : "+String.valueOf("REST_TAMPLATE"));
        System.out.println("[INPUT] : "+String.valueOf(param.toString()));
        System.out.println("================================================");
        System.out.println("\n");


        /**
         * // -----------------------------------------
         * [호출 방법]
         * // -----------------------------------------
         * 1. 호출 방식 : GET
         * // -----------------------------------------
         * 2. 호출 방법 : http://localhost:7000/REST_TAMPLATE
         * // -----------------------------------------
         * 3. 리턴 데이터 : http 요청 리턴 데이터
         * // -----------------------------------------
         * 4. gradle 필요 implementation :
         *
         *   // TODO [RestTemplete http 요청]
         *   implementation 'org.apache.httpcomponents:httpcore:4.4.15'
         *   implementation 'org.apache.httpcomponents:httpclient:4.5.13'
         * // -----------------------------------------
         * */


        // [리턴 데이터 선언 실시]
        HashMap<String, Object> resultMap = new HashMap<String, Object>();


        // [https 요청 객체 선언]
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(20000); // 커넥션 타임 아웃 설정 20초
        factory.setReadTimeout(20000); // 리드 타임 아웃 설정 20초

        HttpClient httpClient = HttpClientBuilder.create()
                .setMaxConnTotal(50)// 최대 커넥션 수
                .setMaxConnPerRoute(20).build();
        factory.setHttpClient(httpClient);


        // [RestTemplate 객체 선언 실시]
        RestTemplate restTemplate = new RestTemplate(factory);


        // [http 헤더 설정]
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<String> entity = new HttpEntity<>(headers);


        // [http 요청 수행 주소 및 데이터 설정]
        String url = "http://jsonplaceholder.typicode.com/posts";

        UriComponents uriBuilder = UriComponentsBuilder.fromHttpUrl(url)
                .queryParam("userId", 1)
                .queryParam("id", 1)
                .build(true);

        // [맵에 설정 값 추가 : 로그]
        resultMap.put("request", uriBuilder.toString());

        try {
            // [http 요청 실시 / GET , POST QueryString]
            ResponseEntity<Object> response = restTemplate.exchange(uriBuilder.toString(), HttpMethod.GET, entity, Object.class);
            //ResponseEntity<Object> response = restTemplate.exchange(uriBuilder.toString(), HttpMethod.POST, entity, Object.class);

            // [http 요청 결과를 Map에 추가]
            resultMap.put("responseStateCode", String.valueOf(response.getStatusCodeValue()));
            resultMap.put("responseBody", String.valueOf(response.getBody()));
        }
        catch (Exception e) {
            e.printStackTrace();

            // [에러 발생 시 map 에 추가 : 로그]
            resultMap.put("exception", String.valueOf(e.getMessage()));
        }


        // [로그 출력 실시]
        System.out.println("\n");
        System.out.println("================================================");
        System.out.println("[CLASS] : "+String.valueOf(CLASS_NAME));
        System.out.println("[METHOD] : "+String.valueOf("REST_TAMPLATE"));
        System.out.println("[RETURN] : "+String.valueOf(resultMap.toString()));
        System.out.println("================================================");
        System.out.println("\n");


        // [Api 리턴 반환]
        return resultMap.toString();
    }
 

[결과 출력]


반응형
Comments