Home 섹션2 서블릿) HTTP 요청 데이터 - API 메시지 바디 - 단순 텍스트
Post
Cancel

섹션2 서블릿) HTTP 요청 데이터 - API 메시지 바디 - 단순 텍스트

본 포스트는 스프링 MVC 1편(김영한, 인프런) 강의를 통해 학습한 내용을 작성자 임의 대로 요약 및 정리한 것입니다.


1. API 메시지 바디 - 단순 텍스트

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

  • HTTP API에서 주로 사용.
    (JSON, XML, TEXT)
  • 데이터 형식은 주로 JSON.
  • POST, PUT, PATCH

  가장 단순한 텍스트 메시지를
HTTP 메시지 바디에 담아 전송, 읽기 해보기!

  HTTP 메시지 바디 데이터를
InputStream 사용해서 직접 읽어보기!

1.1.1. RequestBodyStringServlet

1
2
3
4
5
6
7
8
9
10
11
12
protected void service() throws ~ {
    ServletInputStream inputStream 
            = request.getInputStream();
    String messageBody 
            = StreamUtils.copyToString(inputStream, 
                            StandardCharsets.UTF_8);

    System.out.println("messageBody = " 
                        + messageBody);

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

이렇게 코드를 작성하고
postman으로
http://localhost:8080/request-body-string
rawtext로 “hello!”라고 전송하면,
서버 로그에 아래와 같이 나온다.

1
2
3
4
5
6
7
8
9
10
11
12
Received 
[POST /request-body-string HTTP/1.1
Content-Type: text/plain
User-Agent: PostmanRuntime/7.32.3
Accept: */*
Postman-Token: 308b7c79-248b-40fb-966d-89d141f31715
Host: localhost:8080
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 6

hello!]
1
messageBody = hello!

정상적으로 출력된 걸 확인할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
protected void service() throws ~ {
    ServletInputStream inputStream 
            = request.getInputStream();
    String messageBody 
            = StreamUtils.copyToString(inputStream, 
                            StandardCharsets.UTF_8);

    // System.out.println("messageBody = " 
    //                     + inputStream);
    System.out.println("messageBody = " 
                        + inputStream);

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

만약, 이렇게
inputStream을 직접 찍는다면?

서버 로그에 이렇게 나온다.

1
messageBody = org.apache.catalina.connector.CoyoteInputStream@52fc42ff
Contents