제가 API 호출 하는 방법이요 ? RestTemplate 입니다. (3)(이관 완료)

김민준·2024년 11월 5일

REST API

목록 보기
3/4

티스토리로 이관 중이며 해당글을 좀더 다듬어진 글로 https://mjkim1201.tistory.com/ 로 이관 하였습니다.


💌 개발을 하며 자원을 주고 받는 일이 많다. 외부 서버의 API를 받아서 사용하기도 하고 API를 개발하기도 하는데 REST API 라는 개념에 대해서 자세히 찾아보고 정리해보고자 한다. 정리한 내용을 적어보고 사소한 내용이지만 혹시라도 이 글을 보셔서 최소한 의 지식을 공유 했으면 좋겠다는 바람입니다.

저번 포스트에서는 Spring 프레임워크 이전 API를 호출하는 방식에 대해서 기본 적인 내용이였다면 이번 포스트는 HTTP 통신과 관련하여 Spring 프레임워크가 제공하는 내용을 적어보겠습니다.


RestTemplate

Spring 프레임워크에서 제공하는 RestTemplate 부터 우선 살펴봐야 한다.
Spring 3.0부터 지원되었고, json, xml 응답을 모두 받을 수 있습니다. Rest API 서비스를 요청 후 응답 받을 수 있도록 설계되었습니다.

실제로 사용해본 코드를 바탕으로 내용을 정리해 보고자 합니다.

   private ResponseEntity<String> serverCommunicateResponseEntity
   (String url, HttpMethod method, String jsonData) throws Exception {

       int processId = (int)(Math.random()*10000);
       long initTime = System.currentTimeMillis();

       log.info("[API][{}] AI Service Url: [{}] [{}]",processId,method, url);
       log.info("[API][{}] JsonData: [{}]",processId, jsonData);

       ResponseEntity<String> resultMap = null;
       try {
			UriComponents uri = UriComponentsBuilder.fromHttpUrl(url).build();
           HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
           factory.setConnectTimeout(connTimeout);
           factory.setReadTimeout(readTimeout);
           RestTemplate restTemplate = new RestTemplate(factory);

           //Header 셋팅
           HttpHeaders headers = new HttpHeaders();
           headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

           HttpEntity<String> requestEntity = new HttpEntity<>(jsonData, headers);
           // API를 호출해 Map타입으로 전달 받는다.
           resultMap = restTemplate.exchange(uri.toString(), method, requestEntity, String.class);
           log.info("[API][{}] StatusCode: [{}] RunTime: {}s",processId, resultMap.getStatusCode(),(System.currentTimeMillis()-initTime)/1000.0);

       } catch (HttpClientErrorException | HttpServerErrorException e) {
           log.info("[API][{}] Error StatusCode: [{}] RunTime: {}s",processId, e.getStatusCode().value(),(System.currentTimeMillis()-initTime)/1000.0);
           log.info("[API][{}] Error Message: [{}]",processId, e.getResponseBodyAsString());
           throw e;
       } catch (Exception e) {
           log.info("[API][{}] Error Message: [{}]",processId, e.getMessage());
           throw e;
       }

       return resultMap;
   }

➡️ HttpComponentsClientHttpRequestFactory 이용.

  • HttpComponentsClientHttpRequestFactory 를 이용하여 Connection pool 과 같은 timeout 설정을 진행 할 수 있습니다.
  • 참고로 UriComponentsBuilder 는 Spring에서 제공하는 url를 가독성 있게 만들어주는 기능입니다.
 UriComponents uri = UriComponentsBuilder.fromHttpUrl(url).build();
 HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
 
 factory.setConnectTimeout(connTimeout);
 factory.setReadTimeout(readTimeout);

 RestTemplate restTemplate = new RestTemplate(factory);

  • RestTemplate.class를 살펴보면 호출 메소드인 exchage()가 구현되어 있습니다. 그 중 아래 내용을 참고하였습니다.
  • requestEntity를 넣기 위해서 HttpEntity(String , HttpHeaders) 객체를 생성하였습니다.

 HttpHeaders headers = new HttpHeaders();
             headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

             HttpEntity<String> requestEntity = new HttpEntity<>(jsonData, headers);
             
 resultMap = restTemplate.exchange(uri.toString(), method, requestEntity, String.class);

return resultMap;

0개의 댓글