본문 바로가기
백엔드/Spring(Boot)

HTTP 요청 메시지 (JSON)

by 김어찐 2021. 9. 10.
728x90
import com.fasterxml.jackson.databind.ObjectMapper;
import hello.springmvc.basic.HelloData;
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 javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Controller
public class RequestBodyJsonController {

    private ObjectMapper objectMapper = new ObjectMapper();

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

        log.info("messageBody={}", messageBody);
        HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);
        log.info("helloData = {}",helloData);
        response.getWriter().write("OK");
    }

    @ResponseBody
    @PostMapping("/request-body-json-v2")
    public String requestBodyJsonV2(@RequestBody String messageBody) throws IOException {


        log.info("messageBody={}", messageBody);
        HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);
        log.info("helloData = {}",helloData);
        return "ok";
    }

    @ResponseBody
    @PostMapping("/request-body-json-v3")
    //@RequestBody 생략 불가능 생략하면 @ModelAttribute가 적용된다
    public String requestBodyJsonV3(@RequestBody HelloData helloData) throws IOException {
        log.info("helloData = {}",helloData);
        return "ok";
    }

    @ResponseBody
    @PostMapping("/request-body-json-v4")
    public String requestBodyJsonV4(HttpEntity<HelloData> httpEntity) throws IOException {
        HelloData helloData = httpEntity.getBody();
        log.info("helloData = {}",helloData);
        return "ok";
    }

    @ResponseBody
    @PostMapping("/request-body-json-v5")
    // 객체가 json으로 바껴서 응답한다
    public HelloData requestBodyJsonV5(@RequestBody HelloData helloData) throws IOException {

        log.info("helloData = {}",helloData);
        return helloData;
    }
}
728x90