본문 바로가기

Springあるある

Request Body 전체 조회!!(Feat. HttpEntity)

@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");

}

 

위 코드는 HTML FORM-POST로 요청이 온 경우이다. 

(messageBody : I am Legend)

(messageBody가 예를 들어, GET/POST HTMP FORM 방식이며 messageBody가 username=kim&age=20이라면

각 매개변수를 parsing할 필요가 있으니, request.getParameter(), @RequestParam, @ModelAttribute를 사용하면 되지만, 

"I am legend"와 같이 요청 매개변수가 아닌 경우에는 위 방식을 쓰면 안 된다)

우리가 각가의 매개변수를 받을 때에는 request.getParameter("username") 형식으로 받으면 된다. 

그러나 messageBody에 있는 내용이 요청 매개변수가 아닐 때에는 byte stream 형식으로 받게 되며 그것을 문자 스트림

으로 전환을 해줘야 한다

아래와 같이 HttpEntity를 사용하면 자동으로 스프링이 바이트 스트림을 문자 스트림으로 변환

@PostMapping("/request-body-string-v3") // 필요한 매개변수만 받기!
public HttpEntity<String> requestBodyStringV3(HttpEntity<String> httpEntity) throws IOException {

    String messageBody = httpEntity.getBody();

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

    HttpEntity<String> response = new HttpEntity<>("ok");

    return response;

}