참치코더의 꿈 메모장

Spring / HTTP 요청 메시지(단순 텍스트, JSON) 데이터 스프링 전달 및 응답 방법 정리 본문

Spring

Spring / HTTP 요청 메시지(단순 텍스트, JSON) 데이터 스프링 전달 및 응답 방법 정리

참치깡 2025. 9. 15. 15:34
728x90

 

HTTP 요청 메시지 (단순 텍스트)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Http 요청 메시지 - 단순 텍스트
// Http message body에 데이터를 직접 담아서 요청
 
/*
    1. Http message body에 데이터를 직접 담아서 요청
    2. HTTP API에서 주로 사용, (JSON, XML, TEXT)
    3. 데이터 형식은 주로 JSON 사용
    4. POST, PUT, PATCH 
*/
 
// 요청 파라미터와 다르게, HTTP 메시지 바디를 통해 데이터가 직접 넘어오는 경우는 @RequestParam, @ModelAttribute를 사용할 수 없다.
// (HTML FORM형식으로 전달되는 경우는 요청 파라미터로 인정된다. )
 
 
 
@Slf4j
@Controller
public class RequestBodyStringController {
    
    // 방법 1.
    @PostMapping("/request/body")
    public void requestBodyStringV1(HttpServletRequest request, HttpServletResponse response) throw IOException {
    
        // request body 값 Stream으로 전달 받아 문자열로 변환하기
        ServletInputStream inputStream = request.getInputStream()
        String messageBody = StreamUtils.copyToString(inputStream, standardCharsets.UTF-8);
 
        log.info("messageBody={}", messageBody);
        
 
        // response 서블릿 형태로 body에 "ok" 반환
        response.getWriter().write("ok");
    }
 
    // 방법 2.
    @PostMapping("/request/body")
    public void requestBodyStringV2(InputStream inputStream, Writer responseWriter) throw IOException {
        
        // inputStream을 매개변수로 바로 받아 HTTP body 문자열을 바로 받을 수 있다.
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF-8);
        
        log.info("messageBody={}", messageBody);
        responseWriter.write("ok");
    }
 
    // InputStream(Reader) : Http 요청 메시지 바디의 내용을 직접 조회 한다.
    // OutputStream(Writer) : Http 응답 메시지의 바디에 내용을 직접 출력 한다.
 
    
    // 방법 3.
    @PostMapping("/request/body")
    public HttpEntity<String> requestBodyStringV3(HttpEntity<String> httpEntity) {
        
        String messageBody = httpEntity.getBody(); // Http header, body 정보를 편리하게 조회
        log.info("messageBody={}", messageBody); 
 
        return new HttpEntity<>("ok"); // HttpEntity는 응답에서 사용 가능
    }
 
    // 방법 4. (가장 많이 최근에 사용하는 방법!!!)
    @ResponseBody
    @PostMapping("/request/body")
    public String requestBodyStringV4(@RequestBody String messageBody){
        log.info("messageBody={}", messageBody); // 헤더정보가 필요할 때는 HttpEntity 또는 @RequestHeader를 사용
        return "ok";
    }
    
 
 
}
 
 
 
cs

 

HTTP 요청 메시지 (JSON 데이터 처리)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
    HTTP 요청 메시지 - JSON
 
*/
 
@Slf4j
@Controller
public class RequestBodyJsonController {
    
    private ObjectMapper objectMapper = new ObjectMapper(); 
    
    // 방법 1.
    @PostMapping("/request/body")
    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 data = objectMapper.readValue(messageBody, HelloData.class); // JSON 문자열 -> 자바 객체 변환
        
          log.info("username={}, age={}", data.getUsername(), data.getAge());
 
        response.getWriter.write("ok");
    }
 
    // 방법 2.
    @ResponseBody
    @PostMapping("/request/body"// @RequestBody를 이용한 messageBody String 바로 받기
    public String requestBodyJsonV2(@RequestBody String messageBody) throws IOException {
        
        HelloData data = objectMapper.readValue(messageBody, HellpData.class);  // JSON 문자열 -> 자바 객체 변환
 
        log.info("username={}, age={}", data.getUsername(), data.getAge());
 
        return "ok"// @ResponseBody를 이용한 바로 body에 직접 문자열 반환
    }
 
    // 방법 3. (가장 많이 사용하는 방식 !!!)
    @ResponseBody
    @PostMapping("/request/body")
    public String requestBodyJsonV3(@RequestBody MemberDTO member){
        
          log.info("username={}, age={}", member.getUsername(), member.getAge());
        
          return "ok";
    }
 
    // 방법 4.
    @ResponseBody
    @PostMapping("/request/body")
    public String requestBodyJsonV4(HttpEntity<MemberDTO> httpEntity) {
 
        MemberDto data = httpEntity.getBody();
        log.info("username={}, age={}", data.getUsername(), data.getAge());
 
        return "ok";
    }
}
 
cs
728x90
Comments