관리 메뉴

샐님은 개발중

6. HTTP 요청 메시지 - 단순 텍스트 본문

스프링 MVC 1편 -인프런 김영한/섹션6-스프링MVC - 기본 기능

6. HTTP 요청 메시지 - 단순 텍스트

샐님 2023. 7. 10. 19:18
728x90
반응형

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

 -http api 에서 주로 사용, json, xml, text

-데이터 형식은 주로 json 사용

- post, put, patch

 

요청 파타미터와 다르게 http 메시지 바디를 통해 데이터가 직접 넘어오는 경우는 @RequestParam , @ModelAttribute 를 사용할 수 없다. (물론 HTML Form 형식으로 전달되는 경우는 요청 파라미터로 인정된다.)

 

 

package hello.springmvc.basic.request;

import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.nio.charset.StandardCharsets;

@Slf4j
@Controller
public class RequestBodyStringController {
    @PostMapping("/request-body-string-v1")
    public void requestBodyString(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //InputStream(Reader): HTTP 요청 메시지 바디의 내용을 직접 조회
        
        ServletInputStream inputStream = request.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
        log.info("message body ={}",messageBody);
        response.getWriter().write("ok");
    }

    @PostMapping("/request-body-string-v2")
    public void requestBodyStringV2(InputStream inputStream, Writer responseWriter) throws IOException {

        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
        log.info("message body ={}",messageBody);
        responseWriter.write("ok");
    }

    @PostMapping("/request-body-string-v3")
    public HttpEntity<String> requestBodyStringV3(HttpEntity<String> httpEntity) throws IOException {
		//HttpEntity: HTTP header, body 정보를 편리하게 조회
        String body = httpEntity.getBody();
        log.info("message body ={}",body);

        return new HttpEntity<>("ok");
    }
   //@RequestBody 를 사용하면 HTTP 메시지 바디 정보를 편리하게 조회할 수 있다.
    @ResponseBody
    @PostMapping("/request-body-string-v4")
    public String requestBodyStringV4(@RequestBody String messageBody) throws IOException {
        log.info("message body ={}",messageBody);

        return ("ok");
    }
}
728x90
반응형