2 분 소요


개요

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

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


GET 쿼리 파라미터

쿼리 파라미터는 URL에 ?를 시작으로 보낼 수 있다. 추가 파라미터는 &로 구분.

  • http://localhost:8080/request-param?username=hello&age=20

서버에서는 HttpServletRequest가 제공하는 메서드를 통해 쿼리 파라미터를 편리하게 조회할 수 있다.

//[전체 파라미터 조회]
request.getParameterNames().asIterator()
        .forEachRemaining(paramName -> System.out.println(paramName + "= " + request.getParameter(paramName)));
// username=hello
// age=20

//[단일 파라미터 조회]
String username = request.getParameter("username"); // hello

String age = request.getParameter("age");   // 20

//[이름이 같은 복수 파라미터 조회]
String[] usernames = request.getParameterValues("username");
for (String name : usernames) {
    System.out.println("username=" + name)
}
// username=hello
// username=kim

동일 파라미터 전송
http://localhost:8080/request-param?username=hello&username=kim&age=20


POST HTML Form

특징

  • content-type: applicaion/x-www-form-urlencoded
  • 메시지 바디에 쿼리 파라미터 형식으로 데이터 전달. username=hello&age=20
  • 클라이언트 입장에서는 GET과 POST 방식에 차이가 있지만, 서버 입장에서는 둘의 형식이 동일하므로 request.getParameter()로 구분없이 조회할 수 있다.

[참고]
content-type은 HTTP 메시지 바디의 데이터 형식을 저장한다. GET URL 쿼리 파라미터 형식으로 클라이언트에서 서버로 데이터를 전달할 때는 HTTP 메시지 바디를 사용하지 않기 때문에 content-type이 없다.
POST HTML Form 형식으로 데이터를 전달하면 HTTP 메시지 바디에 해당 데이터를 포함해서 보내기 때문에 데이터가 어떤 형식인지 content-type을 지정해줘야 한다. 이렇게 폼으로 데이터를 전송하는 형식을 application/x-www-form-urlencoded라 한다.


API 메시지 바디

단순 텍스트

  • HTTP message body에 데이터를 직접 담아서 요청
  • HTTP API에서 주로 사용(JSON)
  • HTTP 메시지 바디의 데이터를 InputStream을 사용해서 직접 읽을 수 있다.
ServletInputStream inputStream = request.getInputStream();
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);

[참고] inputStream은 byte 코드를 반환한다. byte 코드를 읽을 수 있는 문자(String)로 보려면 Charset을 지정해주어야 한다.

JSON

JSON 형식 전송

  • content-type: application/json
  • message body: {"username": "hello", "age": 20}
  • 결과: messageBody = {"username": "hello", "age": 20}

JSON 형식 파싱 추가

@Getter @Setter
public class HelloData {

    private String username;
    private int age;
}
private ObjectMapper objectMapper = new ObjectMapper();

@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);

    HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);
    System.out.println("helloData.username = " + helloData.getUsername());
    System.out.println("helloData.age = " + helloData.getAge());
}

출력 결과

messageBody={"username": "hello", "age": 20}
helloData.username = hello
helloData.age = 20

[참고]
JSON 결과를 파싱해서 사용할 수 있는 자바 객체로 변환하려면 Jackson, Gson 같은 JSON 변환 라이브러리를 추가해야 한다.
스프링 부트로 Spring MVC를 선택하면 기본으로 Jackson라이브러리(ObjectMapper)를 함께 제공한다.


<출처 : 인프런 - 스프링 MVC 1편 : 백엔드 웹 개발 핵심 기술(김영한)>

댓글남기기