Spring/SpringMVC

HTTP 요청 데이터 - API 메시지 바디 - 단순 텍스트

느리지만 꾸준하게 2022. 4. 22. 00:39

HTTP 요청 데이터 - API 메시지 바디 - 단순 텍스트

 

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

 

  • HTTP API에서 주로 사용, JSON, XML, TEXT

 

  • 데이터 형식은 주로 JSON 사용

 

  • POST, PUT, PATCH

 

 

  • 먼저 가장 단순한 텍스트 메시지를 HTTP 메시지 바디에 담아서 전송하고, 읽어보자.

 

  • HTTP 메시지 바디의 데이터를 InputStream을 사용해서 직접 읽음

 

 

 

 

 

간단하게 코드로 작성을 해보자.

 

 

// RequestBodyStringServlet class

package hello.setvlet.basic.request;

import org.springframework.util.StreamUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;


@WebServlet(name = "RequestBodyStringServlet", urlPatterns = "/request-body-string")
public class RequestBodyStringServlet extends HttpServlet {
    // http
    // start line
    // header
    //
    // message body
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // message body의 내용을 byte code로 바로 얻을 수 있다.
        ServletInputStream inputStream = request.getInputStream();
        // 스프링이 제공하는 utility 클래스
        // byte를 문자로 알려줄 때 어떤 인코딩인지 반대도 마찬가지
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

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

 

 

 

실행을 시키고 postman으로 테스트를 해보자. 결과를 확인할 수 있다.

 

@WebServlet(name = "RequestBodyStringServlet", urlPatterns = "/request-body-string")

 

 

 

messageBody = hello!

 

 

 

 

 

 

 

이렇게 inputStream을 이용해서 문자전송을 해보았다.

 

  • POST http://localhost:8080/request-body-string

 

  • content-type:text/plain

 

  • message body:hello

 

  • 결과: messageBody = hello

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

<출처 김영한: 스프링 MVC 1편 - 벡앤드 웹 개발 핵심 기술>

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-1/dashboard

 

스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 - 인프런 | 강의

웹 애플리케이션을 개발할 때 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. 스프링 MVC의 핵심 원리와 구조를 이해하고, 더 깊이있는 백엔드 개발자로 성장할 수 있습니다., -

www.inflearn.com