HTTP메세지 바디를 통해 데이터가 직접 넘어오는 경우에는 @RequestParam, @ModelAttribute를 사용할 수 없다.
💡 HTML 폼으로 넘어오는 경우엔 요청 파라미터로 얻을 수 있다.
먼저 가장 간단한 메시지를 HTTP바디에 담아서 전송해보자. HTTP메시지 바디의 데이터는 InputSTream을 사용해 직접 읽을 수 있다.
@Slf4j
@Controller
public class RequestBodyStringController {
@PostMapping("/request0body-string-v1")
public void requestBodyString(HttpServletRequest request,
HttpServletResponse response) throws IOException{
//ServletInputStream이용...
ServletInputStream inputStream = request.getInputStream();
String messageBody = StreamUtils.copyToString(inputStream,
StandardCharsets.UTF_8);
log.info("messageBody={}", messageBody);
response.getWriter().write("ok");
}
결국은 여기도 InputStream을 이용해 데이터를 읽어서 반환한다. 이때 유틸 객체를 이용한다. StreamUtils.copyToString
을 기억합시다..
이때 바이트코드를 문자로 인코딩해야하기때문에 UTF-8을 옵션으로 주자.
이걸 좀 더 업그레이드 해보자.
서블릿 의존성을 없애고 바로 InputStream을 파라미터로 해서 이곳에 받을 수 있다. request.getInputStream
을 생략 가능함.
@PostMapping("/requestBody-string-v2")
//서블릿 의존을 없앤다
public void requestBodyString(InputStream inputStream, Writer responseWriter) throws IOException{
String messageBody = StreamUtils.copyToString(inputStream,
StandardCharsets.UTF_8);
log.info("messageBody={}", messageBody);
responseWriter.write("ok");
}
근데 이게 끝이 아니다…
@PostMapping("/requestBody-string-v3")
//메세지 컨버터
public HttpEntity<String> requestBodyString(HttpEntity<String> httpEntity) throws IOException{
String messageBody = httpEntity.getBody();
log.info("messageBody={}", messageBody);
//첫 인자가 메세지 바디이다
return new HttpEntity<>("ok");
}