[스프링 MVC 1편] HTTP 요청

강신현·2022년 9월 21일
0

✅ HttpServletRequest ✅ InputStream ✅ HttpEntity ✅ @RequestBody ✅ JSON


📕 HTTP 요청

1. 단순 텍스트

HTTP message body에 데이터를 직접 담아서 요청

  • HTTP API에서 주로 사용, JSON, XML, TEXT
  • 데이터 형식은 주로 JSON 사용
  • POST, PUT, PATCH

1) 💡 HttpServletRequest

@PostMapping("/request-body-string-v1")
public void requestBodyString(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ServletInputStream inputStream = request.getInputStream();
    String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

    log.info("messageBody={}", messageBody);
    response.getWriter().write("ok");
}

2) 💡 InputStream

@PostMapping("/request-body-string-v2")
public void requestBodyStringV2(InputStream inputStream, Writer responseWriter) throws IOException {
    String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

    log.info("messageBody={}", messageBody);
    responseWriter.write("ok");
}

3) 💡 HttpEntity

spring 이 자동으로 엔티티 속성에 맞게 넣어줌

  • 응답으로도 사용 가능
@PostMapping("/request-body-string-v3")
public HttpEntity<String> requestBodyStringV3(HttpEntity<String> httpEntity) {
    String messageBody = httpEntity.getBody();

    log.info("messageBody={}", messageBody);
    return new HttpEntity<>("ok");
}

4) 💡 @RequestBody

HTTP 메시지 바디 정보를 편리하게 조회

  • 응답으로도 사용 가능
  • 헤더 정보가 필요한 경우에는 HttpEntity 를 사용하거나 @RequestHeader 를 사용
  • @RequestBody : 메시지 바디를 직접 조회 <-다름-> @RequestParam , @ModelAttribute : 요청 파라미터를 조회
@ResponseBody
@PostMapping("/request-body-string-v4")
public String requestBodyStringV4(@RequestBody String messageBody) {
    log.info("messageBody={}", messageBody);
    return "ok";
}

2. JSON

  • 위처럼 HttpServletRequest, HttpEntity, @RequestBody 등 여러가지 방법으로 요청을 받을 수 있음
@ResponseBody
@PostMapping("/request-body-json-v5")
public HelloData requestBodyJsonV5(@RequestBody HelloData data) {
    log.info("username={}, age={}", data.getUsername(), data.getAge());
    return data;
}
  • 이 경우 HelloData에 @RequestBody 를 생략하면 @ModelAttribute 가 적용되어 요청 파라미터를 처리하게 되므로
    @RequestBody을 생략할 수 없다.

@RequestBody 요청

JSON 요청 -> HTTP 메시지 컨버터 -> 객체

@ResponseBody 응답

객체 -> HTTP 메시지 컨버터 -> JSON 응답


강의 출처

[인프런 - 김영한] 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술

profile
땅콩의 모험 (server)

0개의 댓글