[英]Spring REST (MVC). How to modify http request before handling in the controller
[英]How to get access to HTTP header information in Spring MVC REST controller?
一般來說,我是 Web 編程的新手,尤其是 Java,所以我剛剛了解了 header 和 body 是什么。
我正在使用 Spring MVC 編寫 RESTful 服務。 我能夠在我的控制器中使用@RequestMapping
創建簡單的服務。 我需要幫助了解如何從我的 REST 服務控制器中的方法的請求中獲取 HTTP 標頭信息。 我想解析標題並從中獲取一些屬性。
你能解釋一下我是如何獲取這些信息的嗎?
當您使用@RequestHeader
注釋參數時,該參數會檢索標頭信息。 所以你可以做這樣的事情:
@RequestHeader("Accept")
獲取Accept
標頭。
所以從文檔中:
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive) {
}
Accept-Encoding
和Keep-Alive
標頭值分別在encoding
和keepAlive
參數中提供。
而且不用擔心。 我們都是菜鳥。
您可以使用帶有HttpHeaders
方法參數的@RequestHeader
注釋來訪問所有請求標頭:
@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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.