Search
Duplicate

[Java] RestTemplate 이란, 메소드, 사용예시

순서
4
날짜
2023/03/09
사람
상태
Done
Rest Template 이란?
간편하게 Rest방식의 API를 호출할 수 있는 Spring 내장 클래스이다.
Spring 3.0 부터 지원하며 spring 5.0 이후 부터는 webclient를 사용
Restful 원칙을 지키며, Http의 여러 메서드를 제공한다.
Json, String, XML 모두 응답 받는다.
Blocking I/O 기반의 동기방식을 사용
Header + Content-Type을 설정해 외부와 통신이 가능하다.
RestTemplate 메서드
메서드
HTTP
설명
getForObject
GET
주어진 URL 주소로 GET 메서드로 객체로 결과를 반환
getForEntity
GET
주어진 URL 주소로 GET 메서드로 객체로 결과를 ResponeEntity로 반환
postForLocation
POST
POST요청을 보내고 결과로 헤더에 저장된 URI를 결과로 반환
postForObject
POST
POST 요청을 보내고 객체로 결과를 반환
postForEntity
POST
POST 요청을 보내고 결과로 ResponseEntity로 반환
delete
DELETE
주어진 URL 주소로 DELETE 메서드 실행
headForHeaders
HEADER
헤더의 모든 정보를 얻을 수 있으면 GTTP HEAD 메서드 사용
put
PUT
주어진 URL 주소로 PUT 메서드 실행
patchForObject
PATCH
주어진 URL 주소로 PATCH 메서드 실행
optionsForAllow
OPTIONS
주어진 URL 주소에서 지원하는 HTTP 메서드 조회
exchange
ANY
HTTP 헤더를 새로 만들 수 있고 어떤 HTTP 메서드도 사용 가능
execute
ANY
Request/Response 콜백 수정 가능
RestTemplate 사용 예시
String path = "/restApi/test"; String param = "userId"; HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setConnectTimeout(3000); // 타임아웃 설정 3초 factory.setReadTimeout(3000); // 타임아웃 설정 3초 UriComponentsBuilder builder = UriComponentsBuilder.fromUriString("http//127.0.0.1:8080"); builder.path(path); builder.queryParam(param, param); UriComponents uriComponents = builder.build().encode(); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type", "application/json"); httpHeaders.add("Accept", "*/*"); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity(httpHeaders); UserDTO userDto = null; try { RestTemplate restTemplate = new RestTemplate(factory); ResponseEntity<MinorPurchasableTO> responseEntity = restTemplate.exchange(uriComponents.toUri(), HttpMethod.PUT, requestEntity,UserDTO.class); HttpStatus httpStatus = responseEntity.getStatusCode(); if(HttpStatus.OK.equals(httpStatus)) { userDto = new UserDTO(httpStatus.value()); } }catch (HttpClientErrorException e){ log.error("{}", "error..."); } catch (RuntimeException re){ log.error("{}", "error..."); } return userDto;
Java
복사
후기
오늘은 Spring 에서 많이 사용하는 restApi호출 방법에 대하여 적게되었다. 하면서 문득, 예전에 면접에서 restApi 연동하는 것을 한적이 있는데, 당황했던 적이 떠올랐다. 물론 통과는 하였지만, 나름 정리해두는 것도 좋을 것 같아 적게되었다.