요청메시지 - JSON

인생한접시·2022년 11월 15일
post-thumbnail


HTTP 요청 데이터중 API 메시지 바디 보낼때
단순텍스트 와 JSON 형식으로 보낼 수 있다. 그 중 Json형식을 설명한다.

/**
 * {"username":"hello", "age":20}
 * content-type: application/json
 */
 이렇게 PostJson타입으로 데이터를 보낸걸 받아보도록 하자.

Ver1 - 서블릿

private ObjectMapper objectMapper = new ObjectMapper();

    @PostMapping("/request-body-json-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("username={}, age={}", helloData.getUsername(),
        									helloData.getAge());

        response.getWriter().write("ok");
    }

Ver2 - @RequestBody 문자 변환

    private ObjectMapper objectMapper = new ObjectMapper();

@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("username={}, age={}", 
        	helloData.getUsername(), helloData.getAge());

        return "ok";
    }


(@RequestBody는 요청메시지 - 단순텍스트 페이지에서 배웠다)

Ver3 - @RequestBody 객체 변환

 @ResponseBody
    @PostMapping("/request-body-json-v3")
    public String requestBodyJsonV3(@RequestBody HelloData data) {
        log.info("username={}, age={}",
        	data.getUsername(), data.getAge());
        return "ok";
    }

Ver4 - HttpEntity

  • 물론 앞서 배운 것과 같이 HttpEntity를 사용해도 된다.
@ResponseBody
    @PostMapping("/request-body-json-v4")
    public String requestBodyJsonV4(HttpEntity<HelloData> httpEntity) {
        HelloData data = httpEntity.getBody();
        log.info("username={}, age={}",
        	data.getUsername(), data.getAge());
        return "ok";
    }

Ver5

@ResponseBody
    @PostMapping("/request-body-json-v5")
    public HelloData requestBodyJsonV5(@RequestBody HelloData data) {
        log.info("username={}, age={}",
        	data.getUsername(), data.getAge());
        return data;
    }

profile
plan11plan

0개의 댓글