프로그래밍 일기/Java & Spring

[Spring Boot] RestTemplate 사용법 서버 간 통신 getForEntity, postForEntity

MakeMe 2023. 7. 10. 12:58
반응형
버전정보

Java 11

Spring Boot 2.7.13


RestTemplate 메서드
메서드
HTTP
상세설명
getForObject
GET
URL 주소로 HTTP GET 메서드로 객체로 결과를 반환받는다.
getForEntity
GET
URL 주소로 HTTP GET 메서드로 결과는 ResponseEntity로 반환받는다.
postForLocation
POST
POST 요청을 보내고 결과로 헤더에 저장된 URI를 결과로 반환받는다.
postForObject
POST
POST 요청을 보내고 객체로 결과를 반환받는다.
postForEntity
POST
POST 요청을 보내고 결과로 ResponseEntity로 반환받는다.
delete
DELETE
URL 주소로 HTTP DELETE 메서드를 실행한다.
headForHeaders
HEADER
헤더의 모든 정보를 얻을 수 있으면 HTTP HEAD 메서드를 사용한다.
put
PUT
URL 주소로 HTTP PUT 메서드를 실행한다.
patchForObject
PATCH
URL 주소로 HTTP PATCH 메서드를 실행한다.

일반적으로는 getForObject 보다 getForEntity를 사용합니다. (사용자의 응답 데이터를 확인하기 위함 맨 아래 설명 참고)

getForEntity
    public Map getPostTest(Map params) throws Exception {
        MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
        param.add("name", "Frank Oh");
        param.add("country", "US");

        ResponseEntity<Object> response = new RestTemplate().getForEntity("http://jsonplaceholder.typicode.com/posts", Object.class, param);

        Map result = new HashMap();
        result.put("code", 200);
        result.put("data", response.getBody());
        result.put("message", "success");
        return result;
    }

좌측이 getForObject 우측이 getForEntity ( .getBody() 메서드 실행 시 getForObject와 동일한 값 출력)

postForEntity
    public Map kakaoLogin(Map params) throws Exception {
        HttpHeaders headers = new HttpHeaders();

        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Accept", "application/json");

        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();

        body.add("grant_type", "authorization_code");
        body.add("redirect_uri", "http://localhost:3000/callback/kakao");
        body.add("code", params.get("code").toString());

        HttpEntity httpEntity = new HttpEntity<>(body, headers);
        ResponseEntity<Map> response = new RestTemplate().postForEntity("https://kauth.kakao.com/oauth/token", httpEntity, Map.class);

        return response.getBody();
    }

위 로직은 카카오 로그인 API를 호출하기 위해 사용했던 로직입니다.

 

LinkedMultiValueMap

LinkedMultiValueMap은 key값이 중복될 경우 해당 key값을 list로 변환하여 중복된 key의 value를 저장

 

ResponseEntity

ResponseEntity는 사용자의 HttpRequest에 대한 응답 데이터를 포함하는 클래스입니다. 따라서 HttpStatus, HttpHeader, HttpBody를 포함하고 있습니다.

반응형