JAVA/Spring MVC

[자바 Spring] HTTP Request 헤더(Header) 정보 얻기

_DoYun 2022. 6. 26. 16:32

오늘은 서블릿을 통해 Controller로 Http 요청을 받을 때, 요구사항 속 Request 헤더의 정보를 가져오는 여러가지 방법에 대해 알아보겠습니다. 

 

1. @RequestHeader()

@RestController
@RequestMapping(path = "/Hello/Practice")
public class PracticeFile {

    @PostMapping
    public ResponseEntity headerPractice(@RequestHeader("user-agent") String userAgent,// 핵심코드
                                     @RequestParam("Name") String name,
                                     @RequestParam("phone") String phone,
                                     @RequestParam("price") int price) {
                                     
        System.out.println("user-agent: " + userAgent);
        
        return new ResponseEntity<>(new Coffee(name, phone, price),
                HttpStatus.CREATED);
    }
}

위 코드에서 헤더를 가져오는 코드는 "@RequestHeader("user-agent") String userAgent" 입니다. "user-agent"라는 이름의 헤더의 값을 가져오는 코드입니다. 꼭 "user-agent" 뿐만아니라 일반적으로 요청헤더에 들어있는 헤더들이면 대부분 가능합니다. ex) Content-Type 등

 

**추가

@RestController
@RequestMapping(path = "/Hello/Practice")
public class PracticeFile {

    @PostMapping
    public ResponseEntity headerPractice(@RequestHeader Map<String, String> headers,// 핵심코드
                                     @RequestParam("Name") String name,
                                     @RequestParam("phone") String phone,
                                     @RequestParam("price") int price) {
                                     
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            System.out.println("key: " + entry.getKey() +
                    ", value: " + entry.getValue());
        }
        
        return new ResponseEntity<>(new Coffee(name, phone, price),
                HttpStatus.CREATED);
    }
}

@RequestHeader Map<String, String> headers 코드는 Map을 통해 요청사항 내부에 들어있는 모든 헤더와 그 값들을 Key-Value 형태로 가져오는 코드입니다. 

 

[결과]

key: user-agent, value: PostmanRuntime/7.29.0
key: accept, value: */*
key: cache-control, value: no-cache
key: postman-token, value: 6082ccc2-3195-4726-84ed-6a2009cbae95
key: host, value: localhost:8080
key: accept-encoding, value: gzip, deflate, br
key: connection, value: keep-alive
key: content-type, value: application/x-www-form-urlencoded
key: content-length, value: 54

 

2. HttpServletRequest 객체로 헤더 정보 얻기

@RestController
@RequestMapping(path = "/Hello/Practice")
public class PracticeFile {

    @PostMapping
    public ResponseEntity headerPractice(HttpServletRequest httpServletRequest,// 핵심코드
                                     @RequestParam("Name") String name,
                                     @RequestParam("phone") String phone,
                                     @RequestParam("price") int price) {
                                     
        System.out.println("user-agent: " + httpServletRequest.getHeader("user-agent"));
        
        return new ResponseEntity<>(new Coffee(name, phone, price),
                HttpStatus.CREATED);
    }
}

HttpServletRequest 클래스 내부에 있는 getHeader() 메소드를 활용하여 원하는 이름의 헤더를 가져오는 방법입니다.

 

3. HttpEntity 객체로 헤더 정보 얻기

@RestController
@RequestMapping(path = "/Hello/Practice")
public class PracticeFile {

    @GetMapping
    public ResponseEntity headerPractice(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;);
    }
}