Spring - HttpEntity & ResponseEntity & RequestEntity

박민수·2023년 11월 14일
0

Spring

목록 보기
14/46
post-thumbnail

해당 포스팅에서는 HttpEntity, ResponseEntity, RequestEntity에 대해 간략하게 정리해 보고자 한다.

HttpEntity

HttpEntity는 HTTP 요청 또는 응답 메시지의 header, body 정보를 편리하게 조회 할 수 있는 기능을 제공한다.

  • 메시지 바디 정보를 직접 조회
  • 요청 파라미터를 조회하는 기능과 관계 없음. (@RequestParam X, @ModelAttribute X)
  • HttpMessageConverter 사용 -> StringHttpMessageConverter 적용
  • HttpEntity는 응답에서도 사용 가능하다. (view 조회 X)
  • 메시지 바디 정보 직접 반환
  • 헤더 정보 포함 가능
@PostMapping("/request-body-string")
public HttpEntity<String> requestBodyString(HttpEntity<String> httpEntity) {
    String messageBody = httpEntity.getBody();
    log.info("messageBody={}", messageBody);
    return new HttpEntity<>("ok");
}

RequestEntity

  • HttpEntity의 상속 클래스이며, url 요청을 보낼 때 사용한다.
  • header, body, method, url, type을 생성자 파라미터로 넘길 수 있다.

ResponseEntity

  • HttpEntity를 상속 받아서 HTTP 메시지의 헤더, 바디 정보를 가지고 있다.
  • HTTP 응답 코드를 설정할 수 있다.
  • body, header, status를 생성자 파라미터로 넘길 수 있다.
//HTTP
@GetMapping("/response-body-string")
public ResponseEntity<String> responseBody() {
    return new ResponseEntity<>("ok", HttpStatus.OK);
}

//JSON
@GetMapping("/response-body-json")
public ResponseEntity<HelloData> responseBodyJson() {
    HelloData helloData = new HelloData();
    helloData.setUsername("userA");
    helloData.setAge(20);
    return new ResponseEntity<>(helloData, HttpStatus.OK);
}

참조
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%ED%95%B5%EC%8B%AC-%EC%9B%90%EB%A6%AC-%EA%B8%B0%EB%B3%B8%ED%8E%B8
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-2

profile
안녕하세요 백엔드 개발자입니다.

0개의 댓글