@PostMapping("request-body1")
public void requestBody(HttpServletRequest request, HttpServletResponse response) throws IOException {
ServletInputStream inputStream = request.getInputStream();
String body = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
response.getWriter().write("hello");
}
Body를 받을때 request를 받아 InputStream을 이용할 수 있다.
이를 개선하여 InputStream를 인자를 받아 사용할 수 있다.
@PostMapping("request-body2")
public void requestBody(InputStream inputStream, Writer responseWrite) throws IOException {
String body = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
responseWrite.write("hello");
}
이를 개선해서 HTTP message를 스펙화한 HttpEntity를 사용한다.
body를 문자로 바꿔서 실행한다. 메시지 컨버터가 작동.
@PostMapping("request-body3")
public HttpEntity<String> requestBody(HttpEntity<String> httpEntity) throws IOException {
String body = httpEntity.getBody();
return new HttpEntity<>("hello");
}
이것을 HttpEntity를 상속한 ResponseEntity를 통한 메시지와 상태 코드를 줄 수 있다.
HttpMessageConverter가 작동한다.
@PostMapping("request-body3")
public HttpEntity<String> requestBody(HttpEntity<String> httpEntity) throws IOException {
String body = httpEntity.getBody();
return new ResponseEntity<>("hello", HttpStatus.CREATED);
}
@ResponseBody를 사용하여 Body를 바로 받을 수 있다.
@ResponseBody
@PostMapping("/request-body4")
public HttpEntity<String> requestBody(@RequestBody String body) throws IOException {
return new ResponseEntity<>("hello", HttpStatus.CREATED);
}