HTTP
HTTP Header
HTTP Header 대표적 예시
클라이언트와 서버의 관점에서 내부적으로 가장 많이 사용되는 헤더 정보로 Content-Type
이 있다
Content-Type
Authorization
User-Agent
@RequestHeader
로 개별 헤더 정보 받기
@RestController
@RequestMapping(path = "/v1/coffees")
public class CoffeeController {
@PostMapping
public ResponseEntity postCoffee(@RequestHeader("user-agent") String userAgent,
@RequestParam("korName") String korName,
@RequestParam("engName") String engName,
@RequestParam("price") int price) {
System.out.println("user-agent: " + userAgent);
return new ResponseEntity<>(new Coffee(korName, engName, price),
HttpStatus.CREATED);
}
}
@RequestHeader
로 전체 헤더 정보 받기
@RestController
@RequestMapping(path = "/v1/members")
public class MemberController {
@PostMapping
public ResponseEntity postMember(@RequestHeader Map<String, String> headers,
@RequestParam("email") String email,
@RequestParam("name") String name,
@RequestParam("phone") String phone) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
System.out.println("key: " + entry.getKey() +
", value: " + entry.getValue());
}
return new ResponseEntity<>(new Member(email, name, phone),
HttpStatus.CREATED);
}
}
HttpServletRequest
객체로 헤더 정보 얻기
@RestController
@RequestMapping(path = "/v1/orders")
public class OrderController {
@PostMapping
public ResponseEntity postOrder(HttpServletRequest httpServletRequest,
@RequestParam("memberId") long memberId,
@RequestParam("coffeeId") long coffeeId) {
System.out.println("user-agent: " + httpServletRequest.getHeader("user-agent"));
return new ResponseEntity<>(new Order(memberId, coffeeId),
HttpStatus.CREATED);
}
}
@RequestHeader
를 이용하는 편이 더 용이HttpEntity
객체로 헤더 정보 얻기
@RestController
@RequestMapping(path = "/v1/coffees")
public class CoffeeController{
@GetMapping
public ResponseEntity getCoffees(HttpEntity httpEntity) {
for(Map.Entry<String, List<String>> entry : httpEntity.getHeaders().entrySet()){
System.out.println("key: " + entry.getKey()
+ ", " + "value: " + entry.getValue());
}
System.out.println("host: " + httpEntity.getHeaders().getHost());
return null;
}
}
ResponseEntity
와 HttpHeaders
를 이용해 헤더 정보 추가
@RestController
@RequestMapping(path = "/v1/members")
public class MemberController{
@PostMapping
public ResponseEntity postMember(@RequestParam("email") String email,
@RequestParam("name") String name,
@RequestParam("phone") String phone) {
HttpHeaders headers = new HttpHeaders();
headers.set("Client-Geo-Location", "Korea,Seoul");
return new ResponseEntity<>(new Member(email, name, phone), headers,
HttpStatus.CREATED);
}
}
HttpServletResponse
객체로 헤더 정보 추가
@RestController
@RequestMapping(path = "/v1/members")
public class MemberController{
@GetMapping
public ResponseEntity getMembers(HttpServletResponse response) {
response.addHeader("Client-Geo-Location", "Korea,Seoul");
return null;
}
}
커스텀 헤더(Custom Header) 사용
커스텀 헤더 네이밍(Naming)