HTTP 요청 데이터

zhzkzhffk·2022년 5월 26일
0

본 포스팅은 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술을 보고 정리한 내용입니다.


개요

HTTP 요청 메시지를 통해 클라이언트에서 서버를 데이터를 전달하는 방법

  • GET - 쿼리 파라미터
    • /url?username=hello&age=26
    • 메시지 바디 없이, URL의 쿼리 파라미터에 데이터를 포함해서 전달
    • 예) 검색, 필터, 페이징등에서 많이 사용
  • POST - HTML Form
    • content-type: application/x-www-form-urlencoded
    • 메시지 바디에 쿼리 파리미터 형식으로 전달 username=hello&age=26
    • 예) 회원 가입, 상품 주문, HTML Form 사용
  • HTTP messgae body에 데이터를 직접 담아서 요청
    • HTTP API에서 주로 사용
    • JSON, XML, TEXT
  • 데이터 형식은 주로 JSON 사용
    • POST, PUT, PATCH

HTTP 요청 데이터 - GET 쿼리 파라미터

쿼리파라미터는 URL에 다음과 같이 ?를 시작으로 보낼 수 있다.추가 파라미터는 &로 구분하면 된다.

HTTP 요청 데이터 - POST HTML Form

application/x-www-form-urlencoded 형식은 앞서 GET에서 살펴본 쿼리 파라미터 형식과 같다. 따라서 쿼리 파라미터 조회 메서드를 그대로 사용하면 된다.
클라이언트(웹 브라우저) 입장에서는 두 방식에 차이가 있지만, 서버 입장에서는 둘의 형식이 동일하므로, request.getParameter() 로 편리하게 구분없이 조회할 수 있다.

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

HTTP 메시지 바디의 데이터를 InputStream을 사용해서 직접 읽을 수 있다.

@WebServlet(name = "requestBodyStringServlet", urlPatterns = "/request-body-string")
public class RequestBodyStringServlet extends HttpServlet {
	
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          ServletInputStream inputStream = request.getInputStream();
          String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
          System.out.println("messageBody = " + messageBody);
          response.getWriter().write("ok");
	}
}

inputStream은 byte 코드를 반환 → byte 코드를 우리가 읽을 수 있는 문자(String)로 보려면 문자표 (Charset)를 지정해주어야 한다.

HTTP 요청 데이터 - API 메시지 바디 - JSON

JSON 형식 전송

  • content-type: application/json
  • message body: {"username": "hello", "age": 20}
  • 결과: messageBody = {"username": "hello", "age": 20}
@WebServlet(name = "requestBodyJsonServlet", urlPatterns ="/request-body-json")
public class RequestBodyJsonServlet extends HttpServlet {
        
	private ObjectMapper objectMapper = new ObjectMapper();

	@Override
    protected void service(HttpServletRequest request, HttpServletResponse
    response) throws ServletException, IOException {
    	// JSON → 문자
    	ServletInputStream inputStream = request.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
        
        System.out.println("messageBody = " + messageBody);
        
        // 문자 → 객체
        HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);
        
    	System.out.println("helloData.username = " + helloData.getUsername());
    	System.out.println("helloData.age = " + helloData.getAge());
        
    	response.getWriter().write("ok");
	}
}

JSON 결과를 파싱해서 사용할 수 있는 자바 객체로 변환하려면 Jackson, Gson 같은 JSON 변환 라이브러리를 추가해서 사용해야 한다.

profile
Backend Developer

0개의 댓글