sourcecode

Spring MVC REST 컨트롤러에서 HTTP 헤더 정보에 액세스하려면 어떻게 해야 합니까?

codebag 2023. 2. 15. 21:55
반응형

Spring MVC REST 컨트롤러에서 HTTP 헤더 정보에 액세스하려면 어떻게 해야 합니까?

저는 웹 프로그래밍, 특히 Java에 익숙하지 않기 때문에 헤더와 본문이 무엇인지 알게 되었습니다.

봄 MVC를 이용한 RESTful 서비스를 쓰고 있습니다.를 사용하여 간단한 서비스를 생성할 수 있습니다.@RequestMapping내 컨트롤러에 있습니다.REST 서비스 컨트롤러에서 내 메서드에 도달하는 요청에서 HTTP 헤더 정보를 얻는 방법을 이해하는 데 도움이 필요합니다.헤더를 해석하여 몇 가지 속성을 얻고 싶습니다.

어떻게 하면 그 정보를 얻을 수 있는지 설명해 주시겠습니까?

매개 변수에 주석을 다는 경우@RequestHeader파라미터는 헤더 정보를 가져옵니다.다음과 같이 할 수 있습니다.

@RequestHeader("Accept")

을 손에 넣다Acceptheader를 클릭합니다.

매뉴얼에서는 다음과 같이 기술합니다.

@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
                              @RequestHeader("Keep-Alive") long keepAlive)  {

}

Accept-Encoding그리고.Keep-Alive헤더 값은 에 기재되어 있습니다.encoding그리고.keepAlive파라미터를 지정합니다.

그리고 걱정하지 마세요.우리는 모두 무언가에 집착한다.

를 사용할 수 있습니다.@RequestHeader로의 주석.HttpHeadersmethod 매개 변수를 사용하여 모든 요청 헤더에 액세스할 수 있습니다.

@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers) {
    // Use headers to get the information about all the request headers
    long contentLength = headers.getContentLength();
    // ...
    StreamSource source = new StreamSource(new StringReader(body));
    YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
    // ...
}

예를 들어 user="test"와 같은 헤더 파라미터의 솔루션은 다음과 같습니다.

@RequestMapping(value = "/restURL")
  public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers){

System.out.println(headers.get("user"));
}

HttpEntity를 사용하여 본문과 헤더를 모두 읽을 수 있습니다.

   @RequestMapping(value = "/restURL")
   public String serveRest(HttpEntity<String> httpEntity){
                MultiValueMap<String, String> headers = 
                httpEntity.getHeaders();
                Iterator<Map.Entry<String, List<String>>> s = 
                headers.entrySet().iterator();
                while(s.hasNext()) {
                    Map.Entry<String, List<String>> obj = s.next();
                    String key = obj.getKey();
                    List<String> value = obj.getValue();
                }
                
                String body = httpEntity.getBody();

    }

언급URL : https://stackoverflow.com/questions/19556039/how-to-get-access-to-http-header-information-in-spring-mvc-rest-controller

반응형