Rest api를 개발할 때 사용하는 Content-Type의 역할, 그리고 예제를 통해 어떻게 헤더의 정보를 활용하는지 알아보자.
The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.- w3.org
Http request를 통해 data가 전달될 때, 데이터의 종류를 친절하게 가이드 해 줄수 있는 정보이다. 즉, Content-Type Header을 통해 해당 request에 대한 data(body)에 대한 동작을 제어 할수있다.
Spring boot의 @RestController을 활용하여 간단히 Content-Type이 존재하는 api와 존재하지 않는 api를 작성했다.
둘 다 json형태의 String을 반환한다.
package hello;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CallController {
@GetMapping("/without")
public String withoutType() {
return "{\"name\":\"wonyoung\"}";
}
@GetMapping(value ="/with", produces = "application/json; charset=UTF-8")
public String withType() { //Content-Type에 대한 정의를 추가.
return "{\"name\":\"wonyoung\"}";
}
}
아래는 상기 api를 호출 할 html 코드이다.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#button01").click(function () {
$.ajax({
url: "http://localhost:8090/without",
type: 'GET',
success: function (result) {
alert("result : " + result);
}
});
});
$("#button02").click(function () {
$.ajax({
url: "http://localhost:8090/with",
type: 'GET',
success: function (result) {
alert("result : " + result + "\nresult.name : " + result.name);
}
});
});
});
</script>
</head>
<body>
<button id="button01">Call without content-type</button>
<br>
<button id="button02">Call with content-type</button>
</body>
</html>
스크린샷. html 동작화면
스크린샷. Content-Type이 없는 api를 호출 했을 때 반환 : String으로 auto type casting 됨.
스크린샷. Content-Type이 포함된 api를 호출 했을 때 반환 : Object로 auto type casting 됨.
X-Content-Type-Options: nosniff