HTTP 요청 데이터
HTTP 요청 메세지를 클라이언트에서 서버로 전달하는 방법에 대해 알아보자
주로 3가지 방법을 사용한다.
GET 쿼리 파라미터
메세지 body 없이 URL의 쿼리 파라미터에 데이터를 포함해서 전달하는 방법이다.
ex) /uri?username=hello&age=20
검색, 필터, 페이징 등에서 많이 사용한다.
POST - HTML FORM
메세지 바디에 쿼리 파라미터 형식으로 전달하는 방법이다.
ex) username=hello?age=20
이러한 content-type을 application/x-www-form-urlencoded라고 한다.
회원 가입, 상품 주문, html form에서 사용한다.
HTTP message body에 데이터를 직접 담아서 요청
JSON, XML, TEXT... 형식의 데이터를 body에 담아서 요청하는 방법이다.
HTTP API에서 주로 사용하며, 요청 메서드는 POST, PUT, PATCH가 될 수 있다.
각 방법들을 예시와 함께 살펴보자.
1. GET 쿼리 파라미터
특징
쿼리 파라미터는 URL에 다음과 같이 ?를 시작으로 보낼 수 있다.
추가 파라미터는 '&'로 구분한다. username=hello?age=20
서버에서는 HttpServletRequest가 제공하는 메서드로 쿼리 파라미터를 조회할 수 있다.
함수
- 단일 파라미터 조회
- request.getParamter(String name)
- 파라미터 이름들 모두 조회
- request.getParameterNames()
- 파라미터 값을 이름으로 조회
- request.getParameterName(String name)
- 이름이 같은 복수 파라미터 값 조회
- request.getParameterValues(String name)
예제
Servlet의 service() 함수는 아래와 같이 작성해 주었다.
@WebServlet(name = "requestParamServlet", urlPatterns ="/request-param" )
public class RequestParamServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
파라미터 이름들 모두 조회
request.getParamerNames().asIterator()
.forEachRemaining(paramName->
System.out.println(paramName + "=" + request.getParameter(paramName));
단일 파라미터 조회
request.getParameter("username");
request.getParameter("age");
이름이 중복인 복수 파라미터 조회
String[] usernames = request.getParameterValues("username");
for (String name: usernames){
System.out.println(name);
}
사실 이름이 중복인 경우는 잘 없다.
중복일 때 request.getParameter()를 사용하면, request.getParameterValues() 의 첫 번째 값을 반환한다.
2. POST HTML Form
이번에는 HTML의 Form을 사용해 클라이언트에서 서버로 데이터를 전송해보자
특징
html-form에 데이터를 입력해 전송하면, 웹 브라우저가 content-type을 application/x-www-form-urlencoded 으로 생성해준다.
application/x-www-form-urlencoded 은 메세지 바디에 쿼리 파라미터 형식으로 데이터를 전달한다.
GET은 uri에 쿼리 파라미터 형식으로, POST는 body에 쿼리 파라미터 형식으로 데이터를 전달한다.
서버 입장에서는 둘의 형식이 동일한 것이다. ex) username=hello?age=20
따라서 이전에 작성했던 파라미터 조회 메서드를 그대로 사용하면 된다.
정리하면, request.getParamter()는 GET URL 파라미터 형식도 지원하고, POST HTML Form 형식 둘 다 지원한다.
예제
/request-param에 post 방식으로 보내는 걸 html에 명시했다.
<form action="/request-param" method="post">
hello-form.html에 데이터를 넣으면 파라미터 조회가 가능하다.
참고
content-type은 HTTP 메세지 바디의 데이터 형식을 지정한다.
GET URL 쿼리 파라미터 형식으로 데이터 전달
HTTP 메세지 바디를 사용하지 않으므로 content type이 없다.
POST HTML FORM 형식으로 데이터 전달
HTTP 메세지 바디에 해당 데이터를 포함해서 보낸다.
따라서 바디에 포함된 데이터가 어떤 형식인지 content-type을 지정해야 한다.
위 예시처럼 form으로 데이터를 전송하는 형식을 application/x-www-form-urlencoded라고 한다.
html form을 만들 필요 없이 Postman으로도 조회가 가능하다.
3. API 메세지 바디
HTTP API에서 주로 사용하는 JSON 형식으로 데이터를 전달해보자
- JSON 형식 전송
- POST http://localhost:8080/request-body-json
- content-type: application/json
- message body: {"username": "hello", "age" : 20}
Servlet의 Service()를 작성해준다.
@WebServlet(name = "requestBodyJsonServlet", urlPatterns = "/request-body-json")
public class RequestBodyJsonServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
}
Service() 내부에 아래의 코드를 작성하면 JSON 데이터를 읽을 수 있다.
ServletInputStream inputStream = request.getInputStream();
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
System.out.prinln("messageBody =" + messageBody);
JSON의 결과를 파싱할 수 있는 자바 객체로 변환해보자.
먼저 자바 객체를 생성해준다.
@Getter @Setter
public class HelloData{
private String username;
private int age;
}
ObjectMapper.readValue(Json객체, 자바 객체 클래스) 를 사용하여 변환한다.
private ObjectMapper objectMapper = new ObjectMapper();
..
ServletInputStream inputStream = request.getInputStream();
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);
System.out.println(helloData.getUsername());
System.out.println(helloData.getAge());
Reference
스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 - 인프런 | 강의
웹 애플리케이션을 개발할 때 필요한 모든 웹 기술을 기초부터 이해하고, 완성할 수 있습니다. 스프링 MVC의 핵심 원리와 구조를 이해하고, 더 깊이있는 백엔드 개발자로 성장할 수 있습니다., -
www.inflearn.com