如何在Java中获取HTTP请求标头

时间:2020-02-23 14:34:19  来源:igfitidea点击:

在本教程中,我们将看到如何在Java中获取HTTP请求标头。
有时,要打印请求标题值。

这样做是非常简单的。
我们首先需要获取请求对象,然后调用getheaderfields()上,以获取所有请求标头值。

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
...
        //Get header object
 private HttpServletRequest request;
... 
 public Map getRequestHeaderValues()
 {
                
  Map map = new HashMap();
                //get header values from request object
  Enumeration headerNames = request.getHeaderNames();
  while (headerNames.hasMoreElements()) {
   String key = (String) headerNames.nextElement();
   String value = request.getHeader(key);
   map.put(key, value);
  }
 
  return map;
 }
 
}

Spring MVC:

如果我们使用的是Spring MVC,那么我们可以使用@Autowired注释来获取控制器中的请求对象。

import javax.servlet.http.HttpServletRequest;
 
import org.igi.theitroad.bean.Country;
import org.igi.theitroad.service.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * @author theitroad.com
 * 
 */
@RestController
public class CountryController {
 
 @Autowired
 private HttpServletRequest request;
 CountryService countryService = new CountryService();
 
 @RequestMapping(value = "/countries", method = RequestMethod.GET, headers = "Accept=application/json")
 public List getCountries() {
  
  Enumeration headerNames = request.getHeaderNames();
  while (headerNames.hasMoreElements()) {
   String key = (String) headerNames.nextElement();
   String value = request.getHeader(key);
   System.out.println(key+" : "+value);
  }
  List listOfCountries = countryService.getAllCountries();
  return listOfCountries;
 }
}

我们将获得如下所示的输出:

host : localhost:8080
accept : text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
connection : keep-alive
cookie : JSESSIONID=822C2725DB96155EF6B37CC2A1F5E2A4
user-agent : Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.78.2 (KHTML, like Gecko) Safari/522.0
accept-language : en-us
cache-control : no-cache
accept-encoding : gzip, deflate