HTTP 요청 데이터 -API 메시지 바디 - 단순 텍스트
2024. 8. 24. 14:28ㆍSpring 백엔드 핵심 기술/servlet
HTTP message body에 데이터를 직접 담아서 요청
- HTTP API 에서 주로 사용 JSON, XML, TEXT
- 데이터 형식은 주로 JSON 사용
- POST, PUT, PATCH
-먼저 가장 단순한 텍스트 메시지를 HTTP 메시지 바디에 담아서 전송하고 읽어보자.
-HTTP메시지 바디의 데이터를 InputStream을 사용해서 직접 읽을 수 있다.
package hello.servlet.basic.request;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StreamUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@WebServlet(name = "RequestBodyStringServlet", urlPatterns = "/request-body-string")
public class RequestBodyStringServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletInputStream inputStream = req.getInputStream();
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);//바이트를 문자열로 바꿀때는 인코딩 정보를 알려주어야함
System.out.println("messageBody = " + messageBody);
resp.getWriter().write("ok");
}
}

결과

'Spring 백엔드 핵심 기술 > servlet' 카테고리의 다른 글
| HTTP 응답 데이터 - API JSON (0) | 2024.08.26 |
|---|---|
| HTTP 응답 데이터 - 단순 텍스트, HTML (0) | 2024.08.26 |
| HTTP 요청 데이터 - GET 쿼리 파라미터 (0) | 2024.08.24 |
| HttpServletRequest - 개요2 (0) | 2024.08.24 |
| HttpServletRequest - 개요 (0) | 2024.08.24 |