프로그래밍/사용 라이브러리

RestTamplate : 03. HTTPEntity<T>. HTTP 요청 메시지 생성

Mt.Hwang 2025. 7. 17. 14:33

 * HTTPEntity<T> 주요 메서드

HTTP 요청 또는 응답의 본문과 헤더를 함께 다루기 위해 사용하는 제네릭 클래스
body와 header를 한번에 다룸


T는 요청 혹은 응답의 바디에 담을 데이터 타입을 의미
dto 클래스를 의미


HttpHeaders와 body를 함께 담아 RestTemplate, WebClient, Controller 등에 전달


생성자
 1. HttpEntity() : 헤더와 바디 없이 빈 엔티티 생성
 2. HttpEntity(T body) : 바디만 있는 엔티티 생성
 3. HttpEntity(T body, HttpHeaders headers) : 헤더와 바디 모두 포함한 엔티티 생성


getBody() -> T
 . HTTP 메서드의 body 반환


getHeaders() -> HttpHeaders
 . HTTP 메서드의 헤더 반환


hasBody() -> boolean
 . 본문이 있는지 여부 반환


toString() -> String
 . 전체 HttpEntity 내용을 문자열로 반환


예제
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

MyRequestDto body = new MyRequestDto("hello", 123);

// headers + body 함께 구성
HttpEntity<MyRequestDto> entity = new HttpEntity<>(body, headers);

// 메서드 사용
MyRequestDto bodyValue = entity.getBody();          // 본문 반환
HttpHeaders headerValue = entity.getHeaders();      // 헤더 반환
boolean hasContent = entity.hasBody();              // true