HTTP 헤더(Header)
대표적인 HTTP 헤더 예시
‘Content-Type’
Authorization
User-Agent
개별 헤더 정보 받기
@RestController
@RequestMapping(path = "/coffees")
public class CoffeeController {
@PostMapping
public ResponseEntity postCoffee(@RequestHeader("user-agent") String userAgent,
@RequestParam("name") String name,
@RequestParam("price") int price) {
System.out.println("user-agent: " + userAgent);
return new ResponseEntity<>(new Coffee(name, price), HttpStatus.CREATED);
}
}
전체 헤더 정보 받기
@RestController
@RequestMapping(path = "/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) {
String userAgent = httpServletRequest.getHeader("user-agent");
System.out.println("user-agent: " + userAgent);
return new ResponseEntity<>(new Order(memberId, coffeeId),
HttpStatus.CREATED);
}
}
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());
}
// Host 정보도 가져올 수 있다.
System.out.println("host: " + httpEntity.getHeaders().getHost());
// host: localhost:8080
return null;
}
}
예시
@RestController
@RequestMapping(path = "/members")
public class MemberController{
@PostMapping
public ResponseEntity postMember(@RequestParam("email") String email,
@RequestParam("name") String name,
@RequestParam("phone") String phone) {
// (1) 위치 정보를 헤더에 추가
HttpHeaders headers = new HttpHeaders();
headers.set("Client-Geo-Location", "Korea,Seoul");
return new ResponseEntity<>(new Member(email, name, phone), headers,
HttpStatus.CREATED);
}
}
@RestController
@RequestMapping(path = "/members")
public class MemberController{
@GetMapping
public ResponseEntity getMembers(HttpServletResponse response) {
response.addHeader("Client-Geo-Location", "Korea,Seoul");
return null;
}
}
커스텀 헤더(Custom Header) 사용
커스텀 헤더 네이밍(Naming)
정리가 깔끔하게 잘 되어있네요. 스프링 공부중에 큰 도움 받았습니다. 감사해요.